- + + [fePropertiesMap]="instanceFePropertiesMap" + [readonly]="isReadonly" + [inputs]="inputs | searchFilter:'name':searchQuery" + [instanceNamesMap]="componentInstanceNamesMap" + [isLoading]="loadingInputs" + (deleteInput)="deleteInput($event)" + (inputChanged)="dataChanged($event)"> diff --git a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.less b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.less index 855bdc5bcb..a1309aba61 100644 --- a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.less +++ b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.less @@ -133,13 +133,12 @@ flex-direction:column; margin: 0px 0 0 1em; overflow-x:auto; - .add-btn{ + .add-btn{ align-self: flex-end; margin-top: 10px; margin-bottom: 19px; } - /deep/ .tabs { border-bottom: solid 1px #d0d0d0; } diff --git a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.ts b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.ts index 061439800f..4b84f0e66f 100644 --- a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.ts +++ b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.ts @@ -19,58 +19,34 @@ */ import * as _ from "lodash"; -import {Component, ViewChild, Inject, TemplateRef} from "@angular/core"; +import { Component, ViewChild, Inject, TemplateRef } from "@angular/core"; import { PropertiesService } from "../../services/properties.service"; -import { - PropertyFEModel, - InstanceFePropertiesMap, - InstanceBePropertiesMap, - InstancePropertiesAPIMap, - Component as ComponentData, - FilterPropertiesAssignmentData, - ModalModel, - ButtonModel, - Capability, - ToscaPresentationData -} from "app/models"; +import { PropertyFEModel, InstanceFePropertiesMap, InstanceBePropertiesMap, InstancePropertiesAPIMap, Component as ComponentData, FilterPropertiesAssignmentData, ModalModel, ButtonModel } from "app/models"; import { ResourceType } from "app/utils"; -import {ComponentServiceNg2} from "../../services/component-services/component.service"; -import {ComponentInstanceServiceNg2} from "../../services/component-instance-services/component-instance.service" -import { - InputBEModel, - InputFEModel, - ComponentInstance, - GroupInstance, - PolicyInstance, - PropertyBEModel, - DerivedFEProperty, - SimpleFlatProperty, - CapabilitiesGroup -} from "app/models"; +import { ComponentServiceNg2 } from "../../services/component-services/component.service"; +import { TopologyTemplateService } from "../../services/component-services/topology-template.service"; +import { ComponentInstanceServiceNg2 } from "../../services/component-instance-services/component-instance.service" +import { InputBEModel, InputFEModel, ComponentInstance, GroupInstance, PolicyInstance, PropertyBEModel, DerivedFEProperty, SimpleFlatProperty } from "app/models"; import { KeysPipe } from 'app/ng2/pipes/keys.pipe'; -import {WorkspaceMode, EVENTS} from "../../../utils/constants"; -import {EventListenerService} from "app/services/event-listener-service" -import {HierarchyDisplayOptions} from "../../components/logic/hierarchy-navigtion/hierarchy-display-options"; -import {FilterPropertiesAssignmentComponent} from "../../components/logic/filter-properties-assignment/filter-properties-assignment.component"; -import {PropertyRowSelectedEvent} from "../../components/logic/properties-table/properties-table.component"; -import {HierarchyNavService} from "./services/hierarchy-nav.service"; -import {PropertiesUtils} from "./services/properties.utils"; -import {ComponentModeService} from "../../services/component-services/component-mode.service"; -import {ModalService} from "../../services/modal.service"; -import {Tabs, Tab} from "../../components/ui/tabs/tabs.component"; -import {InputsUtils} from "./services/inputs.utils"; -import {PropertyCreatorComponent} from "./property-creator/property-creator.component"; -import {DeclareListComponent} from "./declare-list/declare-list.component"; +import { WorkspaceMode, EVENTS, PROPERTY_TYPES } from "../../../utils/constants"; +import { EventListenerService } from "app/services/event-listener-service" +import { HierarchyDisplayOptions } from "../../components/logic/hierarchy-navigtion/hierarchy-display-options"; +import { FilterPropertiesAssignmentComponent } from "../../components/logic/filter-properties-assignment/filter-properties-assignment.component"; +import { PropertyRowSelectedEvent } from "../../components/logic/properties-table/properties-table.component"; +import { HierarchyNavService } from "./services/hierarchy-nav.service"; +import { PropertiesUtils } from "./services/properties.utils"; +import { ComponentModeService } from "../../services/component-services/component-mode.service"; +import { Tabs, Tab } from "../../components/ui/tabs/tabs.component"; +import { InputsUtils } from "./services/inputs.utils"; import { InstanceFeDetails } from "../../../models/instance-fe-details"; -import { SdcUiComponents } from "sdc-ui/lib/angular"; -//import { ModalService as ModalServiceSdcUI} from "sdc-ui/lib/angular/modals/modal.service"; -import { IModalButtonComponent } from "sdc-ui/lib/angular/modals/models/modal-config"; +import { SdcUiServices, SdcUiCommon } from "onap-ui-angular"; import { UnsavedChangesComponent } from "app/ng2/components/ui/forms/unsaved-changes/unsaved-changes.component"; -import {Observable} from "rxjs"; -import { DataTypeService } from "app/ng2/services/data-type.service"; -import { DataTypeModel } from "app/models"; -import { PROPERTY_DATA, PROPERTY_TYPES } from "app/utils"; -import { PropertyDeclareAPIModel} from "app/models"; +import {PropertyCreatorComponent} from "./property-creator/property-creator.component"; +import {ModalService} from "../../services/modal.service"; +import { DeclareListComponent } from "./declare-list/declare-list.component"; +import { CapabilitiesGroup, Capability } from "../../../models/capability"; +import { ToscaPresentationData } from "../../../models/tosca-presentation"; +import { Observable } from "rxjs"; const SERVICE_SELF_TITLE = "SELF"; @Component({ @@ -119,7 +95,7 @@ export class PropertiesAssignmentComponent { stateChangeStartUnregister:Function; serviceBePropertiesMap: InstanceBePropertiesMap; serviceBeCapabilitiesPropertiesMap: InstanceBePropertiesMap; - selectedInstance_FlattenCapabilitiesList: Array; + selectedInstance_FlattenCapabilitiesList: Capability[]; @ViewChild('hierarchyNavTabs') hierarchyNavTabs: Tabs; @ViewChild('propertyInputTabs') propertyInputTabs: Tabs; @@ -136,12 +112,13 @@ export class PropertiesAssignmentComponent { @Inject("$state") private $state:ng.ui.IStateService, @Inject("Notification") private Notification:any, private componentModeService:ComponentModeService, - private ModalService:ModalService, private EventListenerService:EventListenerService, - private ModalServiceSdcUI: SdcUiComponents.ModalService) { + private ModalServiceSdcUI: SdcUiServices.ModalService, + private ModalService: ModalService, + private keysPipe:KeysPipe, + private topologyTemplateService: TopologyTemplateService) { this.instanceFePropertiesMap = new InstanceFePropertiesMap(); - /* This is the way you can access the component data, please do not use any data except metadata, all other data should be received from the new api calls on the first time than if the data is already exist, no need to call the api again - Ask orit if you have any questions*/ this.component = _stateParams.component; @@ -159,8 +136,8 @@ export class PropertiesAssignmentComponent { this.loadingPolicies = true; this.loadingInstances = true; this.loadingProperties = true; - this.componentServiceNg2 - .getComponentInputsWithProperties(this.component) + this.topologyTemplateService + .getComponentInputsWithProperties(this.component.componentType, this.component.uniqueId) .subscribe(response => { _.forEach(response.inputs, (input: InputBEModel) => { const newInput: InputFEModel = new InputFEModel(input); @@ -169,7 +146,7 @@ export class PropertiesAssignmentComponent { }); this.loadingInputs = false; - }); + }, error => {}); //ignore error this.componentServiceNg2 .getComponentResourcePropertiesData(this.component) .subscribe(response => { @@ -177,6 +154,7 @@ export class PropertiesAssignmentComponent { this.instances = []; this.instances.push(...response.componentInstances); this.instances.push(...response.groupInstances); + this.instances.push(...response.policies); _.forEach(response.policies, (policy: any) => { const newPolicy: InputFEModel = new InputFEModel(policy); @@ -199,7 +177,7 @@ export class PropertiesAssignmentComponent { this.loadingProperties = false; } this.selectFirstInstanceByDefault(); - }); + }, error => { this.loadingInstances = false; }); //ignore error this.stateChangeStartUnregister = this.$scope.$on('$stateChangeStart', (event, toState, toParams) => { // stop if has changed properties @@ -238,14 +216,14 @@ export class PropertiesAssignmentComponent { getServiceProperties(){ this.loadingProperties = false; - this.componentServiceNg2 - .getServiceProperties(this.component) - .subscribe(response => { + this.topologyTemplateService + .getServiceProperties(this.component.uniqueId) + .subscribe((response) => { this.serviceBePropertiesMap = new InstanceBePropertiesMap(); this.serviceBePropertiesMap[this.component.uniqueId] = response; this.processInstancePropertiesResponse(this.serviceBePropertiesMap, false); this.loadingProperties = false; - }, error => { + }, (error) => { this.loadingProperties = false; }); } @@ -267,14 +245,12 @@ export class PropertiesAssignmentComponent { this.loadingProperties = true; if (instance instanceof ComponentInstance) { let instanceBePropertiesMap: InstanceBePropertiesMap = new InstanceBePropertiesMap(); - this.selectedInstance_FlattenCapabilitiesList = instance.capabilities ? CapabilitiesGroup.getFlattenedCapabilities(instance.capabilities) : []; if (this.isInput(instance.originType)) { this.componentInstanceServiceNg2 .getComponentInstanceInputs(this.component, instance) .subscribe(response => { instanceBePropertiesMap[instance.uniqueId] = response; this.processInstancePropertiesResponse(instanceBePropertiesMap, true); - this.processInstanceCapabilitiesPropertiesResponse(false); this.loadingProperties = false; }, error => { }); //ignore error @@ -286,7 +262,6 @@ export class PropertiesAssignmentComponent { .subscribe(response => { instanceBePropertiesMap[instance.uniqueId] = response; this.processInstancePropertiesResponse(instanceBePropertiesMap, false); - this.processInstanceCapabilitiesPropertiesResponse(false); this.loadingProperties = false; }, error => { }); //ignore error @@ -305,7 +280,7 @@ export class PropertiesAssignmentComponent { } else if (instance instanceof PolicyInstance) { let instanceBePropertiesMap: InstanceBePropertiesMap = new InstanceBePropertiesMap(); this.componentInstanceServiceNg2 - .getComponentPolicyInstanceProperties(this.component, this.selectedInstanceData.uniqueId) + .getComponentPolicyInstanceProperties(this.component.componentType, this.component.uniqueId, this.selectedInstanceData.uniqueId) .subscribe((response) => { instanceBePropertiesMap[instance.uniqueId] = response; this.processInstancePropertiesResponse(instanceBePropertiesMap, false); @@ -480,7 +455,7 @@ export class PropertiesAssignmentComponent { let selectedGroupInstancesProperties: InstanceBePropertiesMap = new InstanceBePropertiesMap(); let selectedPolicyInstancesProperties: InstanceBePropertiesMap = new InstanceBePropertiesMap(); let selectedComponentInstancesInputs: InstanceBePropertiesMap = new InstanceBePropertiesMap(); - let instancesIds = new KeysPipe().transform(this.instanceFePropertiesMap, []); + let instancesIds = this.keysPipe.transform(this.instanceFePropertiesMap, []); angular.forEach(instancesIds, (instanceId: string): void => { let selectedInstanceData: any = this.instances.find(instance => instance.uniqueId == instanceId); @@ -500,7 +475,7 @@ export class PropertiesAssignmentComponent { let inputsToCreate: InstancePropertiesAPIMap = new InstancePropertiesAPIMap(selectedComponentInstancesInputs, selectedComponentInstancesProperties, selectedGroupInstancesProperties, selectedPolicyInstancesProperties); - //move changed capabilities properties from componentInstanceInputsMap obj to componentInstanceProperties + //move changed capabilities properties from componentInstanceInputsMap obj to componentInstanceProperties inputsToCreate.componentInstanceProperties[this.selectedInstanceData.uniqueId] = (inputsToCreate.componentInstanceProperties[this.selectedInstanceData.uniqueId] || []).concat( _.filter( @@ -526,15 +501,14 @@ export class PropertiesAssignmentComponent { } } ); - - this.componentServiceNg2 + this.topologyTemplateService .createInput(this.component, inputsToCreate, this.isSelf()) - .subscribe(response => { + .subscribe((response) => { this.setInputTabIndication(response.length); this.checkedPropertiesCount = 0; this.checkedChildPropertiesCount = 0; _.forEach(response, (input: InputBEModel) => { - let newInput: InputFEModel = new InputFEModel(input); + const newInput: InputFEModel = new InputFEModel(input); this.inputsUtils.resetInputDefaultValue(newInput, input.defaultValue); this.inputs.push(newInput); this.updatePropertyValueAfterDeclare(newInput); @@ -628,8 +602,8 @@ export class PropertiesAssignmentComponent { }; console.log("save button clicked. input=", input); - this.componentServiceNg2 - .createListInput(this.component, input, this.isSelf()) + this.topologyTemplateService + .createListInput(this.component.uniqueId, input, this.isSelf()) .subscribe(response => { this.setInputTabIndication(response.length); this.checkedPropertiesCount = 0; @@ -662,8 +636,8 @@ export class PropertiesAssignmentComponent { console.log('declareListProperties() - leave'); }; - /*** DECLARE PROPERTIES/POLICIES ***/ - declarePropertiesToPolicies = (): void => { + /*** DECLARE PROPERTIES/POLICIES ***/ + declarePropertiesToPolicies = (): void => { let selectedComponentInstancesProperties: InstanceBePropertiesMap = new InstanceBePropertiesMap(); let instancesIds = new KeysPipe().transform(this.instanceFePropertiesMap, []); @@ -679,7 +653,7 @@ export class PropertiesAssignmentComponent { let policiesToCreate: InstancePropertiesAPIMap = new InstancePropertiesAPIMap(null, selectedComponentInstancesProperties, null, null); this.loadingPolicies = true; - this.componentServiceNg2 + this.topologyTemplateService .createPolicy(this.component, policiesToCreate, this.isSelf()) .subscribe(response => { this.setPolicyTabIndication(response.length); @@ -688,7 +662,7 @@ export class PropertiesAssignmentComponent { this.loadingPolicies = false; }); //ignore error - }; + } displayPoliciesAsDeclared = (policies) => { _.forEach(policies, (policy: any) => { @@ -699,8 +673,7 @@ export class PropertiesAssignmentComponent { this.updatePropertyValueAfterDeclare(newPolicy); this.policies.push(policy); }); - }; - + } saveChangedData = ():Promise<(PropertyBEModel|InputBEModel)[]> => { return new Promise((resolve, reject) => { @@ -736,7 +709,8 @@ export class PropertiesAssignmentComponent { if (changedInputsProperties.length && changedCapabilitiesProperties.length) { request = Observable.forkJoin( this.componentInstanceServiceNg2.updateInstanceInputs(this.component, this.selectedInstanceData.uniqueId, changedInputsProperties), - this.componentInstanceServiceNg2.updateInstanceProperties(this.component, this.selectedInstanceData.uniqueId, changedCapabilitiesProperties) + this.componentInstanceServiceNg2.updateInstanceProperties(this.component.componentType, this.component.uniqueId, + this.selectedInstanceData.uniqueId, changedCapabilitiesProperties) ); } else if (changedInputsProperties.length) { @@ -745,7 +719,7 @@ export class PropertiesAssignmentComponent { } else if (changedCapabilitiesProperties.length) { request = this.componentInstanceServiceNg2 - .updateInstanceProperties(this.component, this.selectedInstanceData.uniqueId, changedCapabilitiesProperties); + .updateInstanceProperties(this.component.componentType, this.component.uniqueId, this.selectedInstanceData.uniqueId, changedCapabilitiesProperties); } handleSuccess = (response) => { // reset each changed property with new value and remove it from changed properties list @@ -757,19 +731,18 @@ export class PropertiesAssignmentComponent { }; } else { if (this.isSelf()) { - request = this.componentServiceNg2.updateServiceProperties(this.component, _.map(changedProperties, cp => { + request = this.topologyTemplateService.updateServiceProperties(this.component.uniqueId, _.map(changedProperties, cp => { delete cp.constraints; return cp; })); } else { request = this.componentInstanceServiceNg2 - .updateInstanceProperties(this.component, this.selectedInstanceData.uniqueId, changedProperties); + .updateInstanceProperties(this.component.componentType, this.component.uniqueId, this.selectedInstanceData.uniqueId, changedProperties); } handleSuccess = (response) => { // reset each changed property with new value and remove it from changed properties list response.forEach((resProp) => { - const changedProp = _.find(this.changedData, changedDataObject => changedDataObject.uniqueId === resProp.uniqueId); - this.changedData = _.filter(this.changedData, changedDataObject => changedDataObject.uniqueId !== resProp.uniqueId); + const changedProp = this.changedData.shift(); this.propertiesUtils.resetPropertyValue(changedProp, resProp.value); }); resolve(response); @@ -778,7 +751,7 @@ export class PropertiesAssignmentComponent { } } else if (this.selectedInstanceData instanceof GroupInstance) { request = this.componentInstanceServiceNg2 - .updateComponentGroupInstanceProperties(this.component, this.selectedInstanceData.uniqueId, changedProperties); + .updateComponentGroupInstanceProperties(this.component.componentType, this.component.uniqueId, this.selectedInstanceData.uniqueId, changedProperties); handleSuccess = (response) => { // reset each changed property with new value and remove it from changed properties list response.forEach((resProp) => { @@ -790,7 +763,7 @@ export class PropertiesAssignmentComponent { }; } else if (this.selectedInstanceData instanceof PolicyInstance) { request = this.componentInstanceServiceNg2 - .updateComponentPolicyInstanceProperties(this.component, this.selectedInstanceData.uniqueId, changedProperties); + .updateComponentPolicyInstanceProperties(this.component.componentType, this.component.uniqueId, this.selectedInstanceData.uniqueId, changedProperties); handleSuccess = (response) => { // reset each changed property with new value and remove it from changed properties list response.forEach((resProp) => { @@ -802,6 +775,7 @@ export class PropertiesAssignmentComponent { }; } } else if (this.isInputsTabSelected) { + const changedInputs: InputBEModel[] = this.changedData.map((changedInput) => { changedInput = changedInput; const inputBE = new InputBEModel(changedInput); @@ -925,27 +899,27 @@ export class PropertiesAssignmentComponent { { title: modalTitle, size: 'sm', - type: 'custom', - testId: "id", - + type: SdcUiCommon.ModalType.custom, + testId: "navigate-modal", + buttons: [ - {id: 'cancelButton', text: 'Cancel', type: 'secondary', size: 'xsm', closeModal: true, callback: () => reject()}, - {id: 'discardButton', text: 'Discard', type: 'secondary', size: 'xsm', closeModal: true, callback: () => { this.reverseChangedData(); resolve()}}, - {id: 'saveButton', text: 'Save', type: 'primary', size: 'xsm', closeModal: true, disabled: !this.isValidChangedData, callback: () => this.doSaveChangedData(resolve, reject)} - ] as IModalButtonComponent[] - }, UnsavedChangesComponent, {isValidChangedData: this.isValidChangedData}); + {id: 'cancelButton', text: 'Cancel', type: SdcUiCommon.ButtonType.secondary, size: 'xsm', closeModal: true, callback: () => reject()}, + {id: 'discardButton', text: 'Discard', type: SdcUiCommon.ButtonType.secondary, size: 'xsm', closeModal: true, callback: () => { this.reverseChangedData(); resolve()}}, + {id: 'saveButton', text: 'Save', type: SdcUiCommon.ButtonType.primary, size: 'xsm', closeModal: true, disabled: !this.isValidChangedData, callback: () => this.doSaveChangedData(resolve, reject)} + ] as SdcUiCommon.IModalButtonComponent[] + } as SdcUiCommon.IModalConfig, UnsavedChangesComponent, {isValidChangedData: this.isValidChangedData}); }); } updatePropertyValueAfterDeclare = (input: InputFEModel) => { if (this.instanceFePropertiesMap[input.instanceUniqueId]) { - let instanceName = input.instanceUniqueId.slice(input.instanceUniqueId.lastIndexOf('.') + 1); - let propertyForUpdatindVal = _.find(this.instanceFePropertiesMap[input.instanceUniqueId], (feProperty: PropertyFEModel) => { - return feProperty.uniqueId === input.propertyId && + const instanceName = input.instanceUniqueId.slice(input.instanceUniqueId.lastIndexOf('.') + 1); + const propertyForUpdatindVal = _.find(this.instanceFePropertiesMap[input.instanceUniqueId], (feProperty: PropertyFEModel) => { + return feProperty.name == input.relatedPropertyName && (feProperty.name == input.relatedPropertyName || input.name === instanceName.concat('_').concat(feProperty.name.replace(/[.]/g, '_'))); }); - let inputPath = (input.inputPath && input.inputPath != propertyForUpdatindVal.name) ? input.inputPath : undefined; + const inputPath = (input.inputPath && input.inputPath != propertyForUpdatindVal.name) ? input.inputPath : undefined; propertyForUpdatindVal.setAsDeclared(inputPath); //set prop as declared before assigning value this.propertiesService.disableRelatedProperties(propertyForUpdatindVal, inputPath); this.propertiesUtils.resetPropertyValue(propertyForUpdatindVal, input.relatedPropertyValue, inputPath); @@ -968,7 +942,7 @@ export class PropertiesAssignmentComponent { setPolicyTabIndication = (numPolicies: number): void => { this.propertyInputTabs.setTabIndication('Policies', numPolicies); - }; + } resetUnsavedChangesForInput = (input:InputFEModel) => { this.inputsUtils.resetInputDefaultValue(input, input.defaultValue); @@ -1009,9 +983,9 @@ export class PropertiesAssignmentComponent { deletePolicy = (policy: PolicyInstance) => { this.loadingPolicies = true; - this.componentServiceNg2 + this.topologyTemplateService .deletePolicy(this.component, policy) - .subscribe(response => { + .subscribe((response) => { this.policies = this.policies.filter(policy => policy.uniqueId !== response.uniqueId); //Reload the whole instance for now - TODO: CHANGE THIS after the BE starts returning properties within the response, use commented code below instead! this.changeSelectedInstance(this.selectedInstanceData); @@ -1020,25 +994,25 @@ export class PropertiesAssignmentComponent { }; deleteProperty = (property: PropertyFEModel) => { - let propertyToDelete = new PropertyFEModel(property); + const propertyToDelete = new PropertyFEModel(property); this.loadingProperties = true; - let feMap = this.instanceFePropertiesMap; - this.componentServiceNg2 - .deleteServiceProperty(this.component, propertyToDelete) - .subscribe(response => { + const feMap = this.instanceFePropertiesMap; + this.topologyTemplateService + .deleteServiceProperty(this.component.uniqueId, propertyToDelete) + .subscribe((response) => { const props = feMap[this.component.uniqueId]; props.splice(props.findIndex(p => p.uniqueId === response),1); this.loadingProperties = false; - }, error => { + }, (error) => { this.loadingProperties = false; console.error(error); }); - }; + } /*** addProperty ***/ addProperty = () => { let modalTitle = 'Add Property'; - const modal = this.ModalService.createCustomModal(new ModalModel( + let modal = this.ModalService.createCustomModal(new ModalModel( 'sm', modalTitle, null, @@ -1046,10 +1020,10 @@ export class PropertiesAssignmentComponent { new ButtonModel('Save', 'blue', () => { modal.instance.dynamicContent.instance.isLoading = true; const newProperty: PropertyBEModel = modal.instance.dynamicContent.instance.propertyModel; - this.componentServiceNg2.createServiceProperty(this.component, newProperty) - .subscribe(response => { + this.topologyTemplateService.createServiceProperty(this.component.uniqueId, newProperty) + .subscribe((response) => { modal.instance.dynamicContent.instance.isLoading = false; - let newProp: PropertyFEModel = this.propertiesUtils.convertAddPropertyBAToPropertyFE(response); + const newProp: PropertyFEModel = this.propertiesUtils.convertAddPropertyBAToPropertyFE(response); this.instanceFePropertiesMap[this.component.uniqueId].push(newProp); modal.instance.close(); }, (error) => { @@ -1059,7 +1033,6 @@ export class PropertiesAssignmentComponent { title: 'Failure' }); }); - }, () => !modal.instance.dynamicContent.instance.checkFormValidForSubmit()), new ButtonModel('Cancel', 'outline grey', () => { modal.instance.close(); @@ -1069,24 +1042,23 @@ export class PropertiesAssignmentComponent { )); this.ModalService.addDynamicContentToModal(modal, PropertyCreatorComponent, {}); modal.instance.open(); - }; + } /*** SEARCH RELATED FUNCTIONS ***/ searchPropertiesInstances = (filterData:FilterPropertiesAssignmentData) => { let instanceBePropertiesMap:InstanceBePropertiesMap; this.componentServiceNg2 .filterComponentInstanceProperties(this.component, filterData) - .subscribe(response => { - + .subscribe((response) => { this.processInstancePropertiesResponse(response, false); this.hierarchyPropertiesDisplayOptions.searchText = filterData.propertyName;//mark results in tree this.searchPropertyName = filterData.propertyName;//mark in table this.hierarchyNavTabs.triggerTabChange('Composition'); this.propertiesNavigationData = []; this.displayClearSearch = true; - }, error => {}); //ignore error + }, (error) => {}); //ignore error - }; + } clearSearch = () => { this.instancesNavigationData = this.instances; @@ -1106,5 +1078,6 @@ export class PropertiesAssignmentComponent { private isInput = (instanceType:string):boolean =>{ return instanceType === ResourceType.VF || instanceType === ResourceType.PNF || instanceType === ResourceType.CVFC || instanceType === ResourceType.CR; } + } diff --git a/catalog-ui/src/app/ng2/pages/properties-assignment/property-creator/property-creator.component.ts b/catalog-ui/src/app/ng2/pages/properties-assignment/property-creator/property-creator.component.ts index 7d76904539..5053d52cc8 100644 --- a/catalog-ui/src/app/ng2/pages/properties-assignment/property-creator/property-creator.component.ts +++ b/catalog-ui/src/app/ng2/pages/properties-assignment/property-creator/property-creator.component.ts @@ -1,79 +1,78 @@ -import * as _ from "lodash"; -import {Component} from '@angular/core'; -import {DropdownValue} from "app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component"; -import { DataTypeService } from "app/ng2/services/data-type.service"; -import {PropertyBEModel, DataTypesMap} from "app/models"; -import {PROPERTY_DATA} from "app/utils"; -import {PROPERTY_TYPES} from "../../../../utils"; - +import { Component } from '@angular/core'; +import { DataTypesMap, PropertyBEModel } from 'app/models'; +import { DropdownValue } from 'app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component'; +import { DataTypeService } from 'app/ng2/services/data-type.service'; +import { PROPERTY_DATA } from 'app/utils'; +import * as _ from 'lodash'; +import { PROPERTY_TYPES } from '../../../../utils'; @Component({ selector: 'property-creator', templateUrl: './property-creator.component.html', - styleUrls:['./property-creator.component.less'], + styleUrls: ['./property-creator.component.less'], }) export class PropertyCreatorComponent { - typesProperties: Array; - typesSchemaProperties: Array; + typesProperties: DropdownValue[]; + typesSchemaProperties: DropdownValue[]; propertyModel: PropertyBEModel; - //propertyNameValidationPattern:RegExp = /^[a-zA-Z0-9_:-]{1,50}$/; - //commentValidationPattern:RegExp = /^[\u0000-\u00BF]*$/; - //types:Array; - dataTypes:DataTypesMap; - isLoading:boolean; + // propertyNameValidationPattern:RegExp = /^[a-zA-Z0-9_:-]{1,50}$/; + // commentValidationPattern:RegExp = /^[\u0000-\u00BF]*$/; + // types:Array; + dataTypes: DataTypesMap; + isLoading: boolean; - constructor(protected dataTypeService:DataTypeService) {} + constructor(protected dataTypeService: DataTypeService) {} ngOnInit() { this.propertyModel = new PropertyBEModel(); this.propertyModel.type = ''; this.propertyModel.schema.property.type = ''; - const types: Array = PROPERTY_DATA.TYPES; //All types - simple type + map + list - this.dataTypes = this.dataTypeService.getAllDataTypes(); //Get all data types in service - const nonPrimitiveTypes :Array = _.filter(Object.keys(this.dataTypes), (type:string)=> { - return types.indexOf(type) == -1; + const types: string[] = PROPERTY_DATA.TYPES; // All types - simple type + map + list + this.dataTypes = this.dataTypeService.getAllDataTypes(); // Get all data types in service + const nonPrimitiveTypes: string[] = _.filter(Object.keys(this.dataTypes), (type: string) => { + return types.indexOf(type) === -1; }); this.typesProperties = _.map(PROPERTY_DATA.TYPES, (type: string) => new DropdownValue(type, type) ); - let typesSimpleProperties = _.map(PROPERTY_DATA.SIMPLE_TYPES, + const typesSimpleProperties = _.map(PROPERTY_DATA.SIMPLE_TYPES, (type: string) => new DropdownValue(type, type) ); - let nonPrimitiveTypesValues = _.map(nonPrimitiveTypes, + const nonPrimitiveTypesValues = _.map(nonPrimitiveTypes, (type: string) => new DropdownValue(type, - type.replace("org.openecomp.datatypes.heat.","")) + type.replace('org.openecomp.datatypes.heat.', '')) ) .sort((a, b) => a.label.localeCompare(b.label)); - this.typesProperties = _.concat(this.typesProperties,nonPrimitiveTypesValues); - this.typesSchemaProperties = _.concat(typesSimpleProperties,nonPrimitiveTypesValues); - this.typesProperties.unshift(new DropdownValue('','Select Type...')); - this.typesSchemaProperties.unshift(new DropdownValue('','Select Schema Type...')); + this.typesProperties = _.concat(this.typesProperties, nonPrimitiveTypesValues); + this.typesSchemaProperties = _.concat(typesSimpleProperties, nonPrimitiveTypesValues); + this.typesProperties.unshift(new DropdownValue('', 'Select Type...')); + this.typesSchemaProperties.unshift(new DropdownValue('', 'Select Schema Type...')); } - checkFormValidForSubmit(){ - const showSchema:boolean = this.showSchema(); - let isSchemaValid: boolean = (showSchema && !this.propertyModel.schema.property.type)? false : true; - if (!showSchema){ + checkFormValidForSubmit() { + const showSchema: boolean = this.showSchema(); + const isSchemaValid: boolean = (showSchema && !this.propertyModel.schema.property.type) ? false : true; + if (!showSchema) { this.propertyModel.schema.property.type = ''; } return this.propertyModel.name && this.propertyModel.type && isSchemaValid; } - showSchema():boolean { + showSchema(): boolean { return [PROPERTY_TYPES.LIST, PROPERTY_TYPES.MAP].indexOf(this.propertyModel.type) > -1; - }; + } - onSchemaTypeChange():void { - if (this.propertyModel.type == PROPERTY_TYPES.MAP) { + onSchemaTypeChange(): void { + if (this.propertyModel.type === PROPERTY_TYPES.MAP) { this.propertyModel.value = JSON.stringify({'': null}); - } else if (this.propertyModel.type == PROPERTY_TYPES.LIST) { + } else if (this.propertyModel.type === PROPERTY_TYPES.LIST) { this.propertyModel.value = JSON.stringify([]); } - }; + } } diff --git a/catalog-ui/src/app/ng2/pages/properties-assignment/property-creator/property-creator.module.ts b/catalog-ui/src/app/ng2/pages/properties-assignment/property-creator/property-creator.module.ts index 92accb26b5..1cbb4e17ec 100644 --- a/catalog-ui/src/app/ng2/pages/properties-assignment/property-creator/property-creator.module.ts +++ b/catalog-ui/src/app/ng2/pages/properties-assignment/property-creator/property-creator.module.ts @@ -1,10 +1,10 @@ -import {NgModule} from "@angular/core"; -import {CommonModule} from "@angular/common"; -import {PropertyCreatorComponent} from "./property-creator.component"; -import {FormsModule} from "@angular/forms"; -import {FormElementsModule} from "app/ng2/components/ui/form-components/form-elements.module"; -import {UiElementsModule} from "app/ng2/components/ui/ui-elements.module"; -import {TranslateModule} from "../../../shared/translator/translate.module"; +import { CommonModule } from '@angular/common'; +import { NgModule } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { FormElementsModule } from 'app/ng2/components/ui/form-components/form-elements.module'; +import { UiElementsModule } from 'app/ng2/components/ui/ui-elements.module'; +import { TranslateModule } from '../../../shared/translator/translate.module'; +import { PropertyCreatorComponent } from './property-creator.component'; @NgModule({ declarations: [ diff --git a/catalog-ui/src/app/ng2/pages/properties-assignment/services/properties.utils.ts b/catalog-ui/src/app/ng2/pages/properties-assignment/services/properties.utils.ts index 011be41611..bd7ccd1bfd 100644 --- a/catalog-ui/src/app/ng2/pages/properties-assignment/services/properties.utils.ts +++ b/catalog-ui/src/app/ng2/pages/properties-assignment/services/properties.utils.ts @@ -48,7 +48,7 @@ export class PropertiesUtils { let newFEProp: PropertyFEModel = new PropertyFEModel(property); //Convert property to FE - this.initValueObjectRef(newFEProp); //initialize valueObj. + this.initValueObjectRef(newFEProp); //initialize valueObj AND creates flattened children propertyFeArray.push(newFEProp); newFEProp.updateExpandedChildPropertyId(newFEProp.name); //display only the first level of children this.dataTypeService.checkForCustomBehavior(newFEProp); @@ -79,8 +79,8 @@ export class PropertiesUtils { return instanceFePropertiesMap; } - public convertAddPropertyBAToPropertyFE = (property: PropertyBEModel):PropertyFEModel => { - let newFEProp: PropertyFEModel = new PropertyFEModel(property); //Convert property to FE + public convertAddPropertyBAToPropertyFE = (property: PropertyBEModel): PropertyFEModel => { + const newFEProp: PropertyFEModel = new PropertyFEModel(property); //Convert property to FE this.initValueObjectRef(newFEProp); newFEProp.updateExpandedChildPropertyId(newFEProp.name); //display only the first level of children this.dataTypeService.checkForCustomBehavior(newFEProp); @@ -108,7 +108,7 @@ export class PropertiesUtils { let tempProps: Array = []; let dataTypeObj: DataTypeModel = this.dataTypeService.getDataTypeByTypeName(type); this.dataTypeService.getDerivedDataTypeProperties(dataTypeObj, tempProps, parentName); - return tempProps; + return _.sortBy(tempProps, ['propertiesName']); } /* Sets the valueObj of parent property and its children. diff --git a/catalog-ui/src/app/ng2/pages/req-and-capabilities-editor/capabilities-editor/capabilities-editor.module.ts b/catalog-ui/src/app/ng2/pages/req-and-capabilities-editor/capabilities-editor/capabilities-editor.module.ts index 1e767a5690..104a6d0579 100644 --- a/catalog-ui/src/app/ng2/pages/req-and-capabilities-editor/capabilities-editor/capabilities-editor.module.ts +++ b/catalog-ui/src/app/ng2/pages/req-and-capabilities-editor/capabilities-editor/capabilities-editor.module.ts @@ -5,7 +5,8 @@ import {FormsModule} from "@angular/forms"; import {FormElementsModule} from "app/ng2/components/ui/form-components/form-elements.module"; import {UiElementsModule} from "app/ng2/components/ui/ui-elements.module"; import {TranslateModule} from 'app/ng2/shared/translator/translate.module'; -import {SdcUiComponentsModule} from "sdc-ui/lib/angular/index"; +import { SdcUiComponentsModule } from 'onap-ui-angular'; + @NgModule({ declarations: [ diff --git a/catalog-ui/src/app/ng2/pages/req-and-capabilities-editor/requirements-editor/requirements-editor.module.ts b/catalog-ui/src/app/ng2/pages/req-and-capabilities-editor/requirements-editor/requirements-editor.module.ts index 1be8be51af..d38790a8db 100644 --- a/catalog-ui/src/app/ng2/pages/req-and-capabilities-editor/requirements-editor/requirements-editor.module.ts +++ b/catalog-ui/src/app/ng2/pages/req-and-capabilities-editor/requirements-editor/requirements-editor.module.ts @@ -4,7 +4,7 @@ import {RequirementsEditorComponent} from "./requirements-editor.component"; import {FormsModule} from "@angular/forms"; import {FormElementsModule} from "../../../components/ui/form-components/form-elements.module"; import {TranslateModule} from 'app/ng2/shared/translator/translate.module'; -import {SdcUiComponentsModule} from "sdc-ui/lib/angular/index"; +import { SdcUiComponentsModule } from "onap-ui-angular"; @NgModule({ declarations: [ diff --git a/catalog-ui/src/app/ng2/pages/service-consumption-editor/service-consumption-editor.component.ts b/catalog-ui/src/app/ng2/pages/service-consumption-editor/service-consumption-editor.component.ts index 2c86cc5c5c..8444c6261a 100644 --- a/catalog-ui/src/app/ng2/pages/service-consumption-editor/service-consumption-editor.component.ts +++ b/catalog-ui/src/app/ng2/pages/service-consumption-editor/service-consumption-editor.component.ts @@ -14,29 +14,29 @@ * permissions and limitations under the License. */ -import * as _ from "lodash"; import { Component } from '@angular/core'; -import {ServiceServiceNg2} from "app/ng2/services/component-services/service.service"; import { - Service, - ServiceInstanceObject, - InstanceFePropertiesMap, - InstanceBePropertiesMap, - PropertyBEModel, + Capability, InputBEModel, - OperationModel, + InstanceBePropertiesMap, + InstanceFePropertiesMap, InterfaceModel, - Capability + OperationModel, + PropertyBEModel, + Service } from 'app/models'; -import {ConsumptionInput, ConsumptionInputDetails, ServiceOperation} from 'app/ng2/components/logic/service-consumption/service-consumption.component'; -import {PropertiesUtils} from "app/ng2/pages/properties-assignment/services/properties.utils"; +import { ConsumptionInput, ConsumptionInputDetails, ServiceOperation } from 'app/ng2/components/logic/service-consumption/service-consumption.component'; +import { PropertiesUtils } from 'app/ng2/pages/properties-assignment/services/properties.utils'; +import { ServiceServiceNg2 } from 'app/ng2/services/component-services/service.service'; import { PROPERTY_DATA } from 'app/utils'; - +import * as _ from 'lodash'; +import { ServiceInstanceObject } from '../../../models/service-instance-properties-and-interfaces'; +import { TopologyTemplateService } from '../../services/component-services/topology-template.service'; @Component({ selector: 'service-consumption-editor', templateUrl: './service-consumption-editor.component.html', - styleUrls:['./service-consumption-editor.component.less'], + styleUrls: ['./service-consumption-editor.component.less'], providers: [] }) @@ -45,27 +45,27 @@ export class ServiceConsumptionCreatorComponent { input: { interfaceId: string, serviceOperationIndex: number, - serviceOperations: Array, + serviceOperations: ServiceOperation[], parentService: Service, selectedService: Service, - parentServiceInputs: Array, - selectedServiceProperties: Array, - selectedServiceInstanceId: String, - selectedInstanceSiblings: Array, - selectedInstanceCapabilitisList: Array, - siblingsCapabilitiesList: Map> + parentServiceInputs: InputBEModel[], + selectedServiceProperties: PropertyBEModel[], + selectedServiceInstanceId: string, + selectedInstanceSiblings: ServiceInstanceObject[], + selectedInstanceCapabilitisList: Capability[], + siblingsCapabilitiesList: Map }; - sourceTypes: Array = []; - serviceOperationsList: Array; + sourceTypes: any[] = []; + serviceOperationsList: ServiceOperation[]; serviceOperation: ServiceOperation; currentIndex: number; isLoading: boolean = false; parentService: Service; selectedService: Service; - selectedServiceInstanceId: String; - parentServiceInputs: Array; - selectedServiceProperties: Array; - changedData: Array = []; + selectedServiceInstanceId: string; + parentServiceInputs: InputBEModel[]; + selectedServiceProperties: PropertyBEModel[]; + changedData: ConsumptionInputDetails[] = []; inputFePropertiesMap: any = []; SOURCE_TYPES = { @@ -75,7 +75,7 @@ export class ServiceConsumptionCreatorComponent { SERVICE_INPUT_LABEL: 'Service Input' }; - constructor(private serviceServiceNg2: ServiceServiceNg2, private propertiesUtils:PropertiesUtils) {} + constructor(private topologyTemplateService: TopologyTemplateService, private propertiesUtils: PropertiesUtils) {} ngOnInit() { this.serviceOperationsList = this.input.serviceOperations; @@ -112,7 +112,7 @@ export class ServiceConsumptionCreatorComponent { capabilities: [] } ]; - _.forEach(this.input.selectedInstanceSiblings, sib => + _.forEach(this.input.selectedInstanceSiblings, (sib) => this.sourceTypes.push({ label: sib.name, value: sib.id, @@ -128,56 +128,84 @@ export class ServiceConsumptionCreatorComponent { } onExpandAll() { - _.forEach(this.serviceOperation.consumptionInputs, coInput => { + _.forEach(this.serviceOperation.consumptionInputs, (coInput) => { coInput.expanded = true; - }) + }); } onCollapseAll() { - _.forEach(this.serviceOperation.consumptionInputs, coInput => { + _.forEach(this.serviceOperation.consumptionInputs, (coInput) => { coInput.expanded = false; - }) + }); } isAllInputExpanded() { - return _.every(this.serviceOperation.consumptionInputs, coInput => coInput.expanded === true); + return _.every(this.serviceOperation.consumptionInputs, (coInput) => coInput.expanded === true); } isAllInputCollapsed() { - return _.every(this.serviceOperation.consumptionInputs, coInput => coInput.expanded === false); + return _.every(this.serviceOperation.consumptionInputs, (coInput) => coInput.expanded === false); } onChangePage(newIndex) { if (newIndex >= 0 && newIndex < this.serviceOperationsList.length) { this.currentIndex = newIndex; this.serviceOperation = this.serviceOperationsList[newIndex]; - if(!this.serviceOperation.consumptionInputs || this.serviceOperation.consumptionInputs.length === 0) { + if (!this.serviceOperation.consumptionInputs || this.serviceOperation.consumptionInputs.length === 0) { this.initConsumptionInputs(); } this.getComplexPropertiesForCurrentInputsOfOperation(this.serviceOperation.consumptionInputs); } } + checkFormValidForSubmit(): boolean { + return this.isValidInputsValues() && this.isMandatoryFieldsValid(); + } + + checkFormValidForNavigation(): boolean { + return this.isMandatoryFieldsValid() && (this.changedData.length === 0 || this.isValidInputsValues()); + } + + onChange(value: any, isValid: boolean, consumptionInput: ConsumptionInputDetails) { + consumptionInput.updateValidity(isValid); + const dataChangedIndex = this.changedData.findIndex((changedItem) => changedItem.inputId === consumptionInput.inputId); + if (value !== consumptionInput.origVal) { + if (dataChangedIndex === -1) { + this.changedData.push(consumptionInput); + } + } else { + if (dataChangedIndex !== -1) { + this.changedData.splice(dataChangedIndex, 1); + } + } + } + + onComplexPropertyChanged(property, consumptionInput) { + consumptionInput.value = JSON.stringify(property.valueObj); + this.onChange(property.valueObj, property.valueObjIsValid , consumptionInput); + } + private initConsumptionInputs() { this.isLoading = true; - this.serviceServiceNg2.getServiceConsumptionInputs(this.parentService, this.selectedServiceInstanceId, this.input.interfaceId, this.serviceOperation.operation).subscribe((result: Array) => { + this.topologyTemplateService.getServiceConsumptionInputs(this.parentService.uniqueId, this.selectedServiceInstanceId, + this.input.interfaceId, this.serviceOperation.operation).subscribe((result: ConsumptionInput[]) => { this.isLoading = false; this.serviceOperation.consumptionInputs = this.analyzeCurrentConsumptionInputs(result); this.getComplexPropertiesForCurrentInputsOfOperation(this.serviceOperation.consumptionInputs); - }, err=> { + }, (err) => { this.isLoading = false; }); } - private analyzeCurrentConsumptionInputs(result: Array): Array { - let inputsResult: Array = []; - let currentOp = this.serviceOperation.operation; - if(currentOp) { - inputsResult = _.map(result, input => { - let sourceVal = input.source || this.SOURCE_TYPES.STATIC; - let consumptionInputDetails: ConsumptionInputDetails = _.cloneDeep(input); + private analyzeCurrentConsumptionInputs(result: any[]): ConsumptionInputDetails[] { + let inputsResult: ConsumptionInputDetails[] = []; + const currentOp = this.serviceOperation.operation; + if (currentOp) { + inputsResult = _.map(result, (input) => { + const sourceVal = input.source || this.SOURCE_TYPES.STATIC; + const consumptionInputDetails: ConsumptionInputDetails = _.cloneDeep(input); consumptionInputDetails.source = sourceVal; consumptionInputDetails.isValid = true; consumptionInputDetails.expanded = false; - let filteredListsObj = this.getFilteredProps(sourceVal, input.type); + const filteredListsObj = this.getFilteredProps(sourceVal, input.type); consumptionInputDetails.assignValueLabel = this.getAssignValueLabel(sourceVal); consumptionInputDetails.associatedProps = filteredListsObj.associatedPropsList; consumptionInputDetails.associatedInterfaces = filteredListsObj.associatedInterfacesList; @@ -190,15 +218,14 @@ export class ServiceConsumptionCreatorComponent { private onSourceChanged(consumptionInput: ConsumptionInputDetails): void { consumptionInput.assignValueLabel = this.getAssignValueLabel(consumptionInput.source); - let filteredListsObj = this.getFilteredProps(consumptionInput.source, consumptionInput.type); + const filteredListsObj = this.getFilteredProps(consumptionInput.source, consumptionInput.type); consumptionInput.associatedProps = filteredListsObj.associatedPropsList; consumptionInput.associatedInterfaces = filteredListsObj.associatedInterfacesList; consumptionInput.associatedCapabilities = filteredListsObj.associatedCapabilitiesList; - if(consumptionInput.source === this.SOURCE_TYPES.STATIC) { - if(PROPERTY_DATA.SIMPLE_TYPES.indexOf(consumptionInput.type) !== -1) { - consumptionInput.value = consumptionInput.defaultValue || ""; - } - else { + if (consumptionInput.source === this.SOURCE_TYPES.STATIC) { + if (PROPERTY_DATA.SIMPLE_TYPES.indexOf(consumptionInput.type) !== -1) { + consumptionInput.value = consumptionInput.defaultValue || ''; + } else { consumptionInput.value = null; Object.assign(this.inputFePropertiesMap, this.processPropertiesOfComplexTypeInput(consumptionInput)); } @@ -206,9 +233,11 @@ export class ServiceConsumptionCreatorComponent { } private getFilteredProps(sourceVal, inputType) { - let currentSourceObj = this.sourceTypes.find(s => s.value === sourceVal); - let associatedInterfacesList = [], associatedPropsList = [], associatedCapabilitiesPropsList: Array = []; - if(currentSourceObj) { + const currentSourceObj = this.sourceTypes.find((s) => s.value === sourceVal); + let associatedInterfacesList = []; + let associatedPropsList = []; + let associatedCapabilitiesPropsList: Capability[] = []; + if (currentSourceObj) { if (currentSourceObj.interfaces) { associatedInterfacesList = this.getFilteredInterfaceOutputs(currentSourceObj, inputType); } @@ -221,31 +250,31 @@ export class ServiceConsumptionCreatorComponent { associatedCapabilitiesPropsList = _.reduce(currentSourceObj.capabilities, (filteredCapsList, capability: Capability) => { - let filteredProps = _.filter(capability.properties, prop => prop.type === inputType); + const filteredProps = _.filter(capability.properties, (prop) => prop.type === inputType); if (filteredProps.length) { - let cap = new Capability(capability); + const cap = new Capability(capability); cap.properties = filteredProps; filteredCapsList.push(cap); } - return filteredCapsList + return filteredCapsList; }, []); } return { - associatedPropsList: associatedPropsList, - associatedInterfacesList: associatedInterfacesList, + associatedPropsList, + associatedInterfacesList, associatedCapabilitiesList: associatedCapabilitiesPropsList - } + }; } private getFilteredInterfaceOutputs(currentSourceObj, inputType) { - let currentServiceOperationId = this.serviceOperation.operation.uniqueId; - let filteredInterfacesList = []; - Object.keys(currentSourceObj.interfaces).map(interfId => { - let interfaceObj: InterfaceModel = new InterfaceModel(currentSourceObj.interfaces[interfId]); - Object.keys(interfaceObj.operations).map(opId => { - if(currentServiceOperationId !== opId) { - let operationObj: OperationModel = interfaceObj.operations[opId]; - let filteredOutputsList = _.filter(operationObj.outputs.listToscaDataDefinition, output => output.type === inputType); + const currentServiceOperationId = this.serviceOperation.operation.uniqueId; + const filteredInterfacesList = []; + Object.keys(currentSourceObj.interfaces).map((interfId) => { + const interfaceObj: InterfaceModel = new InterfaceModel(currentSourceObj.interfaces[interfId]); + Object.keys(interfaceObj.operations).map((opId) => { + if (currentServiceOperationId !== opId) { + const operationObj: OperationModel = interfaceObj.operations[opId]; + const filteredOutputsList = _.filter(operationObj.outputs.listToscaDataDefinition, (output) => output.type === inputType); if (filteredOutputsList.length) { filteredInterfacesList.push({ name: `${interfaceObj.type}.${operationObj.name}`, @@ -259,25 +288,23 @@ export class ServiceConsumptionCreatorComponent { return filteredInterfacesList; } - getAssignValueLabel(selectedSource: string): string { - if(selectedSource === this.SOURCE_TYPES.STATIC || selectedSource === "") { + private getAssignValueLabel(selectedSource: string): string { + if (selectedSource === this.SOURCE_TYPES.STATIC || selectedSource === '') { return this.SOURCE_TYPES.STATIC; - } - else { - if(selectedSource === this.parentService.uniqueId) { //parent is the source + } else { + if (selectedSource === this.parentService.uniqueId) { // parent is the source return this.SOURCE_TYPES.SERVICE_INPUT_LABEL; } return this.SOURCE_TYPES.SERVICE_PROPERTY_LABEL; } } - private isValidInputsValues(): boolean { return this.changedData.length > 0 && this.changedData.every((changedItem) => changedItem.isValid); } private isMandatoryFieldsValid(): boolean { - const invalid: Array = this.serviceOperation.consumptionInputs.filter(item => + const invalid: ConsumptionInputDetails[] = this.serviceOperation.consumptionInputs.filter((item) => item.required && (item.value === null || typeof item.value === 'undefined' || item.value === '')); if (invalid.length > 0) { return false; @@ -285,45 +312,19 @@ export class ServiceConsumptionCreatorComponent { return true; } - checkFormValidForSubmit(): boolean { - return this.isValidInputsValues() && this.isMandatoryFieldsValid(); - } - - checkFormValidForNavigation(): boolean { - return this.isMandatoryFieldsValid() && (this.changedData.length === 0 || this.isValidInputsValues()); - } - - onChange(value: any, isValid: boolean, consumptionInput: ConsumptionInputDetails) { - consumptionInput.updateValidity(isValid); - const dataChangedIndex = this.changedData.findIndex((changedItem) => changedItem.inputId === consumptionInput.inputId); - if (value !== consumptionInput.origVal) { - if (dataChangedIndex === -1) { - this.changedData.push(consumptionInput); - } - } else { - if (dataChangedIndex !== -1) { - this.changedData.splice(dataChangedIndex, 1); - } - } - } - - private getComplexPropertiesForCurrentInputsOfOperation(opInputs: Array) { - _.forEach(opInputs, input => { - if(PROPERTY_DATA.SIMPLE_TYPES.indexOf(input.type) === -1 && input.source === this.SOURCE_TYPES.STATIC) { + private getComplexPropertiesForCurrentInputsOfOperation(opInputs: ConsumptionInput[]) { + _.forEach(opInputs, (input) => { + if (PROPERTY_DATA.SIMPLE_TYPES.indexOf(input.type) === -1 && input.source === this.SOURCE_TYPES.STATIC) { Object.assign(this.inputFePropertiesMap, this.processPropertiesOfComplexTypeInput(input)); } }); } private processPropertiesOfComplexTypeInput(input: ConsumptionInput): InstanceFePropertiesMap { - let inputBePropertiesMap: InstanceBePropertiesMap = new InstanceBePropertiesMap(); + const inputBePropertiesMap: InstanceBePropertiesMap = new InstanceBePropertiesMap(); inputBePropertiesMap[input.name] = [input]; - let originTypeIsVF = false; - return this.propertiesUtils.convertPropertiesMapToFEAndCreateChildren(inputBePropertiesMap, originTypeIsVF); //create flattened children and init values + const originTypeIsVF = false; + return this.propertiesUtils.convertPropertiesMapToFEAndCreateChildren(inputBePropertiesMap, originTypeIsVF); // create flattened children and init values } - onComplexPropertyChanged(property, consumptionInput) { - consumptionInput.value = JSON.stringify(property.valueObj); - this.onChange(property.valueObj, property.valueObjIsValid , consumptionInput); - } -} \ No newline at end of file +} diff --git a/catalog-ui/src/app/ng2/pages/service-consumption-editor/service-consumption-editor.module.ts b/catalog-ui/src/app/ng2/pages/service-consumption-editor/service-consumption-editor.module.ts index e37cd76716..43e88eb0dc 100644 --- a/catalog-ui/src/app/ng2/pages/service-consumption-editor/service-consumption-editor.module.ts +++ b/catalog-ui/src/app/ng2/pages/service-consumption-editor/service-consumption-editor.module.ts @@ -1,11 +1,11 @@ -import { NgModule } from "@angular/core"; -import {CommonModule} from "@angular/common"; -import {ServiceConsumptionCreatorComponent} from "./service-consumption-editor.component"; -import {FormsModule} from "@angular/forms"; -import {FormElementsModule} from "app/ng2/components/ui/form-components/form-elements.module"; -import {UiElementsModule} from "app/ng2/components/ui/ui-elements.module"; -import {PropertyTableModule} from 'app/ng2/components/logic/properties-table/property-table.module'; -import {TranslateModule} from 'app/ng2/shared/translator/translate.module'; +import { CommonModule } from '@angular/common'; +import { NgModule } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { PropertyTableModule } from 'app/ng2/components/logic/properties-table/property-table.module'; +import { FormElementsModule } from 'app/ng2/components/ui/form-components/form-elements.module'; +import { UiElementsModule } from 'app/ng2/components/ui/ui-elements.module'; +import { TranslateModule } from 'app/ng2/shared/translator/translate.module'; +import { ServiceConsumptionCreatorComponent } from './service-consumption-editor.component'; @NgModule({ declarations: [ @@ -25,4 +25,4 @@ import {TranslateModule} from 'app/ng2/shared/translator/translate.module'; providers: [] }) export class ServiceConsumptionCreatorModule { -} \ No newline at end of file +} diff --git a/catalog-ui/src/app/ng2/pages/service-dependencies-editor/service-dependencies-editor.component.ts b/catalog-ui/src/app/ng2/pages/service-dependencies-editor/service-dependencies-editor.component.ts index 271dd4ada0..708742ae0c 100644 --- a/catalog-ui/src/app/ng2/pages/service-dependencies-editor/service-dependencies-editor.component.ts +++ b/catalog-ui/src/app/ng2/pages/service-dependencies-editor/service-dependencies-editor.component.ts @@ -14,20 +14,23 @@ * permissions and limitations under the License. */ import { Component } from '@angular/core'; -import {ServiceServiceNg2} from "app/ng2/services/component-services/service.service"; -import {ConstraintObjectUI, OPERATOR_TYPES} from 'app/ng2/components/logic/service-dependencies/service-dependencies.component'; -import {ServiceInstanceObject, PropertyBEModel, InputBEModel} from 'app/models'; +import { InputBEModel, PropertyBEModel } from 'app/models'; +import { ConstraintObjectUI, OPERATOR_TYPES } from 'app/ng2/components/logic/service-dependencies/service-dependencies.component'; +import { DropdownValue } from 'app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component'; +import { ServiceServiceNg2 } from 'app/ng2/services/component-services/service.service'; import { PROPERTY_DATA } from 'app/utils'; -import {DropdownValue} from 'app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component'; +import { ServiceInstanceObject } from '../../../models/service-instance-properties-and-interfaces'; -export class UIDropDownSourceTypesElement extends DropdownValue{ - options: Array; +export class UIDropDownSourceTypesElement extends DropdownValue { + options: any[]; assignedLabel: string; type: string; - constructor(input?: any){ - if(input) { - let value = input.value || ''; - let label = input.label || ''; + constructor(input?: any) { + if (input) { + const value = input.value || ''; + const label = input.label || ''; + // const hidden = input.hidden || ''; + // const selected = input.selected || ''; super(value, label); this.options = input.options; this.assignedLabel = input.assignedLabel; @@ -36,10 +39,11 @@ export class UIDropDownSourceTypesElement extends DropdownValue{ } } +// tslint:disable-next-line:max-classes-per-file @Component({ selector: 'service-dependencies-editor', templateUrl: './service-dependencies-editor.component.html', - styleUrls:['./service-dependencies-editor.component.less'], + styleUrls: ['./service-dependencies-editor.component.less'], providers: [ServiceServiceNg2] }) @@ -47,44 +51,42 @@ export class ServiceDependenciesEditorComponent { input: { serviceRuleIndex: number, - serviceRules: Array, + serviceRules: ConstraintObjectUI[], compositeServiceName: string, currentServiceName: string, - parentServiceInputs: Array, - selectedInstanceProperties: Array, - operatorTypes: Array, - selectedInstanceSiblings: Array + parentServiceInputs: InputBEModel[], + selectedInstanceProperties: PropertyBEModel[], + operatorTypes: DropdownValue[], + selectedInstanceSiblings: ServiceInstanceObject[] }; currentServiceName: string; - selectedServiceProperties: Array; + selectedServiceProperties: PropertyBEModel[]; selectedPropertyObj: PropertyBEModel; - ddValueSelectedServicePropertiesNames: Array; - operatorTypes: Array; - sourceTypes: Array = []; + ddValueSelectedServicePropertiesNames: DropdownValue[]; + operatorTypes: DropdownValue[]; + sourceTypes: UIDropDownSourceTypesElement[] = []; currentRule: ConstraintObjectUI; currentIndex: number; - listOfValuesToAssign: Array; - listOfSourceOptions: Array; + listOfValuesToAssign: DropdownValue[]; + listOfSourceOptions: PropertyBEModel[]; assignedValueLabel: string; - serviceRulesList: Array; - + serviceRulesList: ConstraintObjectUI[]; SOURCE_TYPES = { STATIC: {label: 'Static', value: 'static'}, SERVICE_PROPERTY: {label: 'Service Property', value: 'property'} }; - ngOnInit() { this.currentIndex = this.input.serviceRuleIndex; this.serviceRulesList = this.input.serviceRules; this.currentRule = this.serviceRulesList && this.input.serviceRuleIndex >= 0 ? - this.serviceRulesList[this.input.serviceRuleIndex]: - new ConstraintObjectUI({sourceName: this.SOURCE_TYPES.STATIC.value, sourceType: this.SOURCE_TYPES.STATIC.value, value: "", constraintOperator: OPERATOR_TYPES.EQUAL}); + this.serviceRulesList[this.input.serviceRuleIndex] : + new ConstraintObjectUI({sourceName: this.SOURCE_TYPES.STATIC.value, sourceType: this.SOURCE_TYPES.STATIC.value, value: '', constraintOperator: OPERATOR_TYPES.EQUAL}); this.currentServiceName = this.input.currentServiceName; this.operatorTypes = this.input.operatorTypes; this.selectedServiceProperties = this.input.selectedInstanceProperties; - this.ddValueSelectedServicePropertiesNames = _.map(this.input.selectedInstanceProperties, prop => new DropdownValue(prop.name, prop.name)); + this.ddValueSelectedServicePropertiesNames = _.map(this.input.selectedInstanceProperties, (prop) => new DropdownValue(prop.name, prop.name)); this.initSourceTypes(); this.syncRuleData(); this.updateSourceTypesRelatedValues(); @@ -100,7 +102,7 @@ export class ServiceDependenciesEditorComponent { type: this.SOURCE_TYPES.SERVICE_PROPERTY.value, options: this.input.parentServiceInputs }); - _.forEach(this.input.selectedInstanceSiblings, sib => + _.forEach(this.input.selectedInstanceSiblings, (sib) => this.sourceTypes.push({ label: sib.name, value: sib.name, @@ -112,28 +114,27 @@ export class ServiceDependenciesEditorComponent { } syncRuleData() { - if(!this.currentRule.sourceName && this.currentRule.sourceType === this.SOURCE_TYPES.STATIC.value) { + if (!this.currentRule.sourceName && this.currentRule.sourceType === this.SOURCE_TYPES.STATIC.value) { this.currentRule.sourceName = this.SOURCE_TYPES.STATIC.value; } - this.selectedPropertyObj = _.find(this.selectedServiceProperties, prop => prop.name === this.currentRule.servicePropertyName); + this.selectedPropertyObj = _.find(this.selectedServiceProperties, (prop) => prop.name === this.currentRule.servicePropertyName); this.updateOperatorTypesList(); this.updateSourceTypesRelatedValues(); } updateOperatorTypesList() { if (this.selectedPropertyObj && PROPERTY_DATA.SIMPLE_TYPES_COMPARABLE.indexOf(this.selectedPropertyObj.type) === -1) { - this.operatorTypes = [{label: "=", value: OPERATOR_TYPES.EQUAL}]; + this.operatorTypes = [{label: '=', value: OPERATOR_TYPES.EQUAL}]; this.currentRule.constraintOperator = OPERATOR_TYPES.EQUAL; - } - else { + } else { this.operatorTypes = this.input.operatorTypes; } } updateSourceTypesRelatedValues() { - if(this.currentRule.sourceName) { - let selectedSourceType: UIDropDownSourceTypesElement = this.sourceTypes.find( - t => t.value === this.currentRule.sourceName && t.type === this.currentRule.sourceType + if (this.currentRule.sourceName) { + const selectedSourceType: UIDropDownSourceTypesElement = this.sourceTypes.find( + (t) => t.value === this.currentRule.sourceName && t.type === this.currentRule.sourceType ); this.listOfSourceOptions = selectedSourceType.options || []; this.assignedValueLabel = selectedSourceType.assignedLabel || this.SOURCE_TYPES.STATIC.label; @@ -150,7 +151,7 @@ export class ServiceDependenciesEditorComponent { } onServicePropertyChanged() { - this.selectedPropertyObj = _.find(this.selectedServiceProperties, prop => prop.name === this.currentRule.servicePropertyName); + this.selectedPropertyObj = _.find(this.selectedServiceProperties, (prop) => prop.name === this.currentRule.servicePropertyName); this.updateOperatorTypesList(); this.filterOptionsByType(); this.currentRule.value = ''; @@ -165,11 +166,11 @@ export class ServiceDependenciesEditorComponent { } filterOptionsByType() { - if(!this.selectedPropertyObj) { + if (!this.selectedPropertyObj) { this.listOfValuesToAssign = []; return; } - this.listOfValuesToAssign = this.listOfSourceOptions.reduce((result, op:PropertyBEModel) => { + this.listOfValuesToAssign = this.listOfSourceOptions.reduce((result, op: PropertyBEModel) => { if (op.type === this.selectedPropertyObj.type && (!op.schemaType || op.schemaType === this.selectedPropertyObj.schemaType)) { result.push(new DropdownValue(op.name, op.name)); } @@ -182,11 +183,11 @@ export class ServiceDependenciesEditorComponent { } checkFormValidForSubmit() { - if(!this.serviceRulesList) { //for create modal - let isStatic = this.currentRule.sourceName === this.SOURCE_TYPES.STATIC.value; + if (!this.serviceRulesList) { // for create modal + const isStatic = this.currentRule.sourceName === this.SOURCE_TYPES.STATIC.value; return this.currentRule.isValidRule(isStatic); } - //for update all rules - return this.serviceRulesList.every(rule => rule.isValidRule(rule.sourceName === this.SOURCE_TYPES.STATIC.value)); + // for update all rules + return this.serviceRulesList.every((rule) => rule.isValidRule(rule.sourceName === this.SOURCE_TYPES.STATIC.value)); } -} \ No newline at end of file +} diff --git a/catalog-ui/src/app/ng2/pages/service-dependencies-editor/service-dependencies-editor.module.ts b/catalog-ui/src/app/ng2/pages/service-dependencies-editor/service-dependencies-editor.module.ts index 98ac997bf7..7b128f4468 100644 --- a/catalog-ui/src/app/ng2/pages/service-dependencies-editor/service-dependencies-editor.module.ts +++ b/catalog-ui/src/app/ng2/pages/service-dependencies-editor/service-dependencies-editor.module.ts @@ -1,9 +1,9 @@ -import { NgModule } from "@angular/core"; -import {CommonModule} from "@angular/common"; -import {ServiceDependenciesEditorComponent} from "./service-dependencies-editor.component"; -import {FormsModule} from "@angular/forms"; -import {FormElementsModule} from "app/ng2/components/ui/form-components/form-elements.module"; -import {UiElementsModule} from "app/ng2/components/ui/ui-elements.module"; +import { CommonModule } from '@angular/common'; +import { NgModule } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { FormElementsModule } from 'app/ng2/components/ui/form-components/form-elements.module'; +import { UiElementsModule } from 'app/ng2/components/ui/ui-elements.module'; +import { ServiceDependenciesEditorComponent } from './service-dependencies-editor.component'; @NgModule({ declarations: [ @@ -22,4 +22,4 @@ import {UiElementsModule} from "app/ng2/components/ui/ui-elements.module"; providers: [] }) export class ServiceDependenciesEditorModule { -} \ No newline at end of file +} diff --git a/catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.less b/catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.less deleted file mode 100644 index beec9bd567..0000000000 --- a/catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.less +++ /dev/null @@ -1,21 +0,0 @@ -@import './../../../../../assets/styles/variables.less'; -.remove { - display: flex; - align-items: center; - justify-content: center; -} - -.cell { - padding: 0; -} - -/deep/ .link-selector { - select { - height: 30px; - border: none; - stroke: none; - } - -} - - diff --git a/catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.ts b/catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.ts deleted file mode 100644 index e4fc1d4522..0000000000 --- a/catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.ts +++ /dev/null @@ -1,103 +0,0 @@ -import {Component, Input} from '@angular/core'; -import {DropdownValue} from "app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component"; -import {Link} from './link.model'; -import {ServicePathMapItem} from "app/models/graph/nodes-and-links-map"; - -@Component({ - selector: 'link-row', - templateUrl: './link-row.component.html', - styleUrls: ['./link-row.component.less'] -}) - - -export class LinkRowComponent { - @Input() data:Array; - @Input() link:Link; - @Input() removeRow:Function; - source: Array = []; - target: Array = []; - srcCP: Array = []; - targetCP: Array = []; - - ngOnChanges() { - if (this.data) { - this.parseInitialData(this.data); - } - } - - parseInitialData(data: Array) { - this.source = this.convertValuesToDropDownOptions(data); - if (this.link.fromNode) { - let srcCPOptions = this.findOptions(data, this.link.fromNode); - if (!srcCPOptions) { return; } - this.srcCP = this.convertValuesToDropDownOptions(srcCPOptions); - if (this.link.fromCP) { - this.target = this.convertValuesToDropDownOptions(data); - if (this.link.toNode) { - let targetCPOptions = this.findOptions(data, this.link.toNode); - if (!targetCPOptions) { return; } - this.targetCP = this.convertValuesToDropDownOptions(targetCPOptions); - } - } - } - } - - private findOptions(items: Array, nodeOrCPId: string) { - let item = _.find(items, (dataItem) => nodeOrCPId === dataItem.id); - if (item && item.data && item.data.options) { - return item.data.options; - } - console.warn('no option was found to match selection of Node/CP with id:' + nodeOrCPId); - return null; - } - - private convertValuesToDropDownOptions(values: Array): Array { - let result:Array = []; - for (let i = 0; i < values.length ; i++) { - result[result.length] = new DropdownValue(values[i].id, values[i].data.name); - } - return result.sort((a, b) => a.label.localeCompare(b.label)); - } - - onSourceSelected(id) { - if (id) { - let srcCPOptions = this.findOptions(this.data, id); - this.srcCP = this.convertValuesToDropDownOptions(srcCPOptions); - this.link.fromCP = ''; - this.link.toNode = ''; - this.link.toCP = ''; - this.target = []; - this.targetCP = []; - } - } - - onSrcCPSelected (id) { - if (id) { - let srcCPOptions = this.findOptions(this.data, this.link.fromNode); - let srcCPData = srcCPOptions.find(option => id === option.id).data; - this.target = this.convertValuesToDropDownOptions(this.data); - this.link.fromCPOriginId = srcCPData.ownerId; - this.link.toNode = ''; - this.link.toCP = ''; - this.targetCP = []; - } - - } - - onTargetSelected(id) { - if (id) { - let targetCPOptions = this.findOptions(this.data, id); - this.targetCP = this.convertValuesToDropDownOptions(targetCPOptions); - this.link.toCP = ''; - } - - } - - onTargetCPSelected(id) { - if (id) { - let targetCPOptions = this.findOptions(this.data, this.link.toNode); - let targetCPDataObj = targetCPOptions.find(option => id === option.id).data; - this.link.toCPOriginId = targetCPDataObj.ownerId; - } - } -} diff --git a/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.html b/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.html deleted file mode 100644 index cc14b4961f..0000000000 --- a/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.html +++ /dev/null @@ -1,56 +0,0 @@ - - -
-
-
- - -
- -
-
- - -
-
- - -
-
- -
- Based On - Extend Flow -
- -
-
-
- {{header}} -
-
-
- There is no data to display -
-
- -
-
- - -
-
\ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.less b/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.less deleted file mode 100644 index 5c9e53e229..0000000000 --- a/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.less +++ /dev/null @@ -1,45 +0,0 @@ -@import './../../../../assets/styles/variables.less'; -.service-path-creator { - font-family: @font-opensans-regular; - .separator-buttons { - margin: 10px 0; - display: flex; - justify-content: space-between; - } - .i-sdc-form-label { - font-size: 12px; - } - .w-sdc-form .i-sdc-form-item { - margin-bottom: 15px; - } - - .side-by-side { - display: flex; - .i-sdc-form-item { - flex-basis: 100%; - &:first-child { - margin-right: 10px; - } - } - } - - .generic-table { - max-height: 233px; - .header-row .header-cell { - &:last-child { - padding: 0; - } - } - /deep/ .cell { - &:last-child { - min-width: 30px; - } - } - } - - .based-on-title { - text-transform: uppercase; - font-size: 18px; - font-family: @font-opensans-regular; - } -} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.ts b/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.ts deleted file mode 100644 index bffb1c5e7e..0000000000 --- a/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.ts +++ /dev/null @@ -1,147 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -import * as _ from "lodash"; -import { Component, ElementRef, forwardRef, Inject } from '@angular/core'; -import {Link} from './link-row/link.model'; -import {ForwardingPath} from 'app/models/forwarding-path'; -import {ServiceServiceNg2} from "app/ng2/services/component-services/service.service"; -import {ForwardingPathLink} from "app/models/forwarding-path-link"; -import {ServicePathMapItem} from "app/models/graph/nodes-and-links-map"; - -@Component({ - selector: 'service-path-creator', - templateUrl: './service-path-creator.component.html', - styleUrls:['./service-path-creator.component.less'], - providers: [ServiceServiceNg2] -}) - -export class ServicePathCreatorComponent { - - linksMap:Array; - links:Array = []; - input:any; - headers: Array = []; - removeRow: Function; - forwardingPath:ForwardingPath; - //isExtendAllowed:boolean = false; - - constructor(private serviceService: ServiceServiceNg2) { - this.forwardingPath = new ForwardingPath(); - this.links = [new Link(new ForwardingPathLink('', '', '', '', '', ''), true, false, true)]; - this.headers = ['Source', 'Source Connection Point', 'Target', 'Target Connection Point', ' ']; - this.removeRow = () => { - if (this.links.length === 1) { - return; - } - this.links.splice(this.links.length-1, 1); - this.enableCurrentRow(); - }; - } - - ngOnInit() { - this.serviceService.getNodesAndLinksMap(this.input.service).subscribe((res:any) => { - this.linksMap = res; - }); - this.processExistingPath(); - - } - - private processExistingPath() { - if (this.input.pathId) { - let forwardingPath = {...this.input.service.forwardingPaths[this.input.pathId]}; - this.forwardingPath.name = forwardingPath.name; - this.forwardingPath.destinationPortNumber = forwardingPath.destinationPortNumber; - this.forwardingPath.protocol = forwardingPath.protocol; - this.forwardingPath.uniqueId = forwardingPath.uniqueId; - this.links = []; - _.forEach(forwardingPath.pathElements.listToscaDataDefinition, (link:ForwardingPathLink) => { - this.links[this.links.length] = new Link(link, false, false, false); - }); - this.links[this.links.length - 1].canEdit = true; - this.links[this.links.length - 1].canRemove = true; - this.links[0].isFirst = true; - } - } - - isExtendAllowed():boolean { - if (this.links[this.links.length-1].toCP) { - return true; - } - return false; - } - - enableCurrentRow() { - this.links[this.links.length-1].canEdit = true; - if (this.links.length !== 1) { - this.links[this.links.length-1].canRemove = true; - } - } - - addRow() { - this.disableRows(); - this.links[this.links.length] = new Link( - new ForwardingPathLink(this.links[this.links.length-1].toNode, - this.links[this.links.length-1].toCP, - '', - '', - this.links[this.links.length-1].toCPOriginId, - '' - ), - true, - true, - false - ); - } - - disableRows() { - for (let i = 0 ; i < this.links.length ; i++) { - this.links[i].canEdit = false; - this.links[i].canRemove = false; - } - } - - createPathLinksObject() { - for (let i = 0 ; i < this.links.length ; i++) { - let link = this.links[i]; - this.forwardingPath.addPathLink(link.fromNode, link.fromCP, link.toNode, link.toCP, link.fromCPOriginId, link.toCPOriginId); - } - } - - createServicePathData() { - this.createPathLinksObject(); - return this.forwardingPath; - } - - checkFormValidForSubmit():boolean { - if (this.forwardingPath.name && this.isPathValid() ) { - return true; - } - return false; - } - - isPathValid():boolean { - let lastLink = this.links[this.links.length -1] ; - if (lastLink.toNode && lastLink.toCP && lastLink.fromNode && lastLink.fromCP) { - return true; - } - return false; - } -} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.html b/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.html deleted file mode 100644 index 33a0090372..0000000000 --- a/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.html +++ /dev/null @@ -1,37 +0,0 @@ - - -
- -
-
-
- {{header}} -
-
-
-
{{path.name}}
-
- - -
-
-
- No flows have been added yet. -
-
- -
\ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.less b/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.less deleted file mode 100644 index 291119f58c..0000000000 --- a/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.less +++ /dev/null @@ -1,24 +0,0 @@ -@import './../../../../assets/styles/variables.less'; - -.add-path-link { - display: flex; - align-items: flex-end; - flex-direction: column; - padding-bottom: 10px; -} - -.generic-table { - max-height: 233px; -} - -.path-action-buttons { - display: flex; - align-items: center; - justify-content: space-between; - .sprite-new { - cursor: pointer; - } - & > span:only-child { - margin: auto; -} -} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.ts b/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.ts deleted file mode 100644 index 1625ab4b66..0000000000 --- a/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.ts +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -import * as _ from "lodash"; -import {Component, ComponentRef} from '@angular/core'; -import {ForwardingPath} from "app/models/forwarding-path"; -import {ServiceServiceNg2} from "app/ng2/services/component-services/service.service"; -import {ModalService} from "app/ng2/services/modal.service"; -import {ModalComponent} from "app/ng2/components/ui/modal/modal.component"; - -@Component({ - selector: 'service-paths-list', - templateUrl: './service-paths-list.component.html', - styleUrls:['service-paths-list.component.less'], - providers: [ServiceServiceNg2, ModalService] -}) -export default class ServicePathsListComponent { - modalInstance: ComponentRef; - headers: Array = []; - paths: Array = []; - input:any; - onAddServicePath: Function; - onEditServicePath: Function; - isViewOnly: boolean; - - constructor(private serviceService:ServiceServiceNg2) { - this.headers = ['Flow Name','Actions']; - } - - ngOnInit() { - _.forEach(this.input.service.forwardingPaths, (path: ForwardingPath)=> { - this.paths[this.paths.length] = path; - }); - this.paths.sort((a:ForwardingPath, b:ForwardingPath)=> { - return a.name.localeCompare(b.name); - }); - this.onAddServicePath = this.input.onCreateServicePath; - this.onEditServicePath = this.input.onEditServicePath; - this.isViewOnly = this.input.isViewOnly; - } - - deletePath = (id:string):void => { - this.serviceService.deleteServicePath(this.input.service, id).subscribe((res:any) => { - delete this.input.service.forwardingPaths[id]; - this.paths = this.paths.filter(function(path){ - return path.uniqueId !== id; - }); - }); - }; - -} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.module.ts b/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.module.ts deleted file mode 100644 index c236934002..0000000000 --- a/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.module.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { NgModule } from "@angular/core"; -import {CommonModule} from "@angular/common"; -import ServicePathsListComponent from "./service-paths-list.component"; - -@NgModule({ - declarations: [ - ServicePathsListComponent - ], - imports: [CommonModule], - exports: [], - entryComponents: [ - ServicePathsListComponent - ], - providers: [] -}) -export class ServicePathsListModule { -} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/activity-log/activity-log.component.html b/catalog-ui/src/app/ng2/pages/workspace/activity-log/activity-log.component.html new file mode 100644 index 0000000000..d7cf2f930a --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/activity-log/activity-log.component.html @@ -0,0 +1,68 @@ + +
+
+ + +
+ + + + + {{row.TIMESTAMP | date }} | {{row.TIMESTAMP | date:"HH:mm O"}} + + + + + {{row.ACTION}} + + + + + {{ row.COMMENT }} + + + + + {{ row.MODIFIER }} + + + + + + + + + + +
\ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/activity-log/activity-log.component.less b/catalog-ui/src/app/ng2/pages/workspace/activity-log/activity-log.component.less new file mode 100644 index 0000000000..4845f4f606 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/activity-log/activity-log.component.less @@ -0,0 +1,8 @@ +.sdc-filter-bar-wrapper { + sdc-filter-bar { + flex: 0 0 30%; + } + display: flex; + justify-content: flex-end; + margin-bottom: 10px; +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/activity-log/activity-log.component.spec.ts b/catalog-ui/src/app/ng2/pages/workspace/activity-log/activity-log.component.spec.ts new file mode 100644 index 0000000000..25651e0c1f --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/activity-log/activity-log.component.spec.ts @@ -0,0 +1,84 @@ +import { NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture } from '@angular/core/testing'; +import { NgxDatatableModule } from '@swimlane/ngx-datatable'; +import { SdcUiServices } from 'onap-ui-angular'; +import 'rxjs/add/observable/of'; +import { Observable } from 'rxjs/Observable'; +import { ConfigureFn, configureTests } from '../../../../../jest/test-config.helper'; +import { ComponentMetadata } from '../../../../models/component-metadata'; +import { ActivityLogService } from '../../../services/activity-log.service'; +import { WorkspaceService } from '../workspace.service'; +import { ActivityLogComponent } from './activity-log.component'; + +describe('activity log component', () => { + + let fixture: ComponentFixture; + let activityLogServiceMock: Partial; + let workspaceServiceMock: Partial; + let loaderServiceMock: Partial; + let componentMetadataMock: ComponentMetadata; + + const mockLogs = '[' + + '{"MODIFIER":"Carlos Santana(m08740)","COMMENT":"comment","STATUS":"200","ACTION":"Checkout","TIMESTAMP":"2018-11-19 13:00:02.388 UTC"},' + + '{"MODIFIER":"John Doe(m08741)","COMMENT":"comment","STATUS":"200","ACTION":"Checkin","TIMESTAMP":"2018-11-20 13:00:02.388 UTC"},' + + '{"MODIFIER":"Jane Doe(m08742)","COMMENT":"comment","STATUS":"200","ACTION":"Checkout","TIMESTAMP":"2018-11-21 13:00:02.388 UTC"}' + + ']'; + + beforeEach( + async(() => { + + componentMetadataMock = new ComponentMetadata(); + componentMetadataMock.uniqueId = 'fake'; + componentMetadataMock.componentType = 'SERVICE'; + + activityLogServiceMock = { + getActivityLog : jest.fn().mockImplementation((type, id) => Observable.of(JSON.parse(mockLogs)) ) + }; + + workspaceServiceMock = { + metadata : componentMetadataMock + }; + + loaderServiceMock = { + activate : jest.fn(), + deactivate: jest.fn() + }; + + const configure: ConfigureFn = (testBed) => { + testBed.configureTestingModule({ + declarations: [ActivityLogComponent], + imports: [NgxDatatableModule], + schemas: [NO_ERRORS_SCHEMA], + providers: [ + { provide: WorkspaceService, useValue: workspaceServiceMock }, + { provide: ActivityLogService, useValue: activityLogServiceMock }, + { provide: SdcUiServices.LoaderService, useValue: loaderServiceMock } + ], + }); + }; + + configureTests(configure).then((testBed) => { + fixture = testBed.createComponent(ActivityLogComponent); + }); + }) + ); + + it('should see exactly 3 activity logs', () => { + fixture.componentInstance.ngOnInit(); + expect(fixture.componentInstance.activities.length).toBe(3); + }); + + it('should filter out 1 element when searching', () => { + fixture.componentInstance.ngOnInit(); + + const event = { + target : { + value : 'Checkin' + } + }; + + expect(fixture.componentInstance.activities.length).toBe(3); + fixture.componentInstance.updateFilter(event); + expect(fixture.componentInstance.activities.length).toBe(1); + }); +}); diff --git a/catalog-ui/src/app/ng2/pages/workspace/activity-log/activity-log.component.ts b/catalog-ui/src/app/ng2/pages/workspace/activity-log/activity-log.component.ts new file mode 100644 index 0000000000..84fb81a1ef --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/activity-log/activity-log.component.ts @@ -0,0 +1,48 @@ +import { Component, OnInit, ViewChild } from '@angular/core'; +import { SdcUiServices } from 'onap-ui-angular'; +import { Activity } from '../../../../models/activity'; +import { ActivityLogService } from '../../../services/activity-log.service'; +import { WorkspaceService } from '../workspace.service'; + +@Component({ + selector: 'activity-log', + templateUrl: './activity-log.component.html', + styleUrls: ['./activity-log.component.less', '../../../../../assets/styles/table-style.less'] +}) +export class ActivityLogComponent implements OnInit { + + activities: Activity[] = []; + temp: Activity[] = []; + + constructor(private workspaceService: WorkspaceService, + private activityLogService: ActivityLogService, + private loaderService: SdcUiServices.LoaderService) { + } + + ngOnInit(): void { + this.loaderService.activate(); + const componentId: string = this.workspaceService.metadata.uniqueId; + const componentType: string = this.workspaceService.metadata.componentType; + this.activityLogService.getActivityLog(componentType, componentId).subscribe((logs) => { + this.activities = logs; + this.temp = [...logs]; + this.loaderService.deactivate(); + }, (error) => { this.loaderService.deactivate(); }); + } + + updateFilter(event) { + const val = event.target.value.toLowerCase(); + + // filter our data + const temp = this.temp.filter((activity: Activity) => { + return !val || + activity.COMMENT.toLowerCase().indexOf(val) !== -1 || + activity.STATUS.toLowerCase().indexOf(val) !== -1 || + activity.ACTION.toLowerCase().indexOf(val) !== -1 || + activity.MODIFIER.toLowerCase().indexOf(val) !== -1; + }); + + // update the rows + this.activities = temp; + } +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/activity-log/activity-log.module.ts b/catalog-ui/src/app/ng2/pages/workspace/activity-log/activity-log.module.ts new file mode 100644 index 0000000000..39334d8cde --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/activity-log/activity-log.module.ts @@ -0,0 +1,28 @@ +import {CommonModule} from "@angular/common"; +import {NgModule} from "@angular/core"; +import {SdcUiComponentsModule} from "onap-ui-angular"; +import {GlobalPipesModule} from "../../../pipes/global-pipes.module"; +import {ActivityLogComponent} from "./activity-log.component"; +import {ActivityLogService} from "../../../services/activity-log.service"; +import {NgxDatatableModule} from "@swimlane/ngx-datatable"; + +@NgModule({ + declarations: [ + ActivityLogComponent + ], + imports: [ + CommonModule, + SdcUiComponentsModule, + GlobalPipesModule, + NgxDatatableModule + ], + exports: [ + ActivityLogComponent + ], + entryComponents: [ + ActivityLogComponent + ], + providers: [ ActivityLogService ] +}) +export class ActivityLogModule { +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/attributes/attribute-modal.component.html b/catalog-ui/src/app/ng2/pages/workspace/attributes/attribute-modal.component.html new file mode 100644 index 0000000000..bd30a469e0 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/attributes/attribute-modal.component.html @@ -0,0 +1,104 @@ +
+
+ +
+ +
+ + + + + + +
+ + +
+ + +
+
+ +
+ +
+ + + + + + +
+ + +
+ + + + + + + +
+ + +
+ + + +
+ +
+ + + + + + +
+ + + + +
+
+ +
\ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/attributes/attribute-modal.component.ts b/catalog-ui/src/app/ng2/pages/workspace/attributes/attribute-modal.component.ts new file mode 100644 index 0000000000..c703869ad2 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/attributes/attribute-modal.component.ts @@ -0,0 +1,138 @@ +import { Component, OnInit, ViewChild } from '@angular/core'; +import { IDropDownOption } from 'onap-ui-angular/dist/form-elements/dropdown/dropdown-models'; +import { InputComponent } from 'onap-ui-angular/dist/form-elements/text-elements/input/input.component'; +import { Subject } from 'rxjs/Subject'; +import { AttributeModel } from '../../../../models/attributes'; +import { ValidationUtils } from '../../../../utils/validation-utils'; +import { CacheService } from '../../../services/cache.service'; +import { TranslateService } from '../../../shared/translator/translate.service'; +import { AttributeOptions } from './attributes-options'; + +@Component({ + selector: 'attribute-modal', + templateUrl: './attribute-modal.component.html', + styleUrls: ['./attributes.component.less'] +}) +export class AttributeModalComponent implements OnInit { + + @ViewChild('defaultValue') validatedInput: InputComponent; + + public readonly types = AttributeOptions.types; // integer, string, boolean etc. + + public readonly booleanValues = AttributeOptions.booleanValues; // true / false + + public readonly entrySchemaValues = AttributeOptions.entrySchemaValues; // integer, string, boolean, float + + public onValidationChange: Subject = new Subject(); + + public validationPatterns: any; + public readonly listPattern = ValidationUtils.getPropertyListPatterns(); + public readonly mapPattern = ValidationUtils.getPropertyMapPatterns(); + + // The current effective default value pattern + public defaultValuePattern: string; + public defaultValueErrorMessage: string; + + // Attribute being Edited + public attributeToEdit: AttributeModel; + + constructor(private translateService: TranslateService, private cacheService: CacheService) { + this.validationPatterns = this.cacheService.get('validation').validationPatterns; + } + + ngOnInit() { + this.revalidateDefaultValue(); + } + + onHiddenCheckboxClicked(event: boolean) { + this.attributeToEdit.hidden = event; + } + + onTypeSelected(selectedElement: IDropDownOption) { + if (this.attributeToEdit.type !== selectedElement.value && selectedElement.value === 'boolean') { + this.attributeToEdit.defaultValue = ''; // Clean old value in case we choose change type to boolean + } + this.attributeToEdit.type = selectedElement.value; + this.revalidateDefaultValue(); + } + + onBooleanDefaultValueSelected(selectedElement: IDropDownOption) { + if (this.attributeToEdit.type === 'boolean') { + this.attributeToEdit.defaultValue = selectedElement.value; + } + } + + onEntrySchemaTypeSelected(selectedElement: IDropDownOption) { + this.attributeToEdit.schema.property.type = selectedElement.value; + this.revalidateDefaultValue(); + } + + onValidityChange(isValid: boolean, field: string) { + const typeIsValid = this.attributeToEdit.type && this.attributeToEdit.type.length > 0; // Make sure type is defined + + // Make sure name is defined when other fields are changed + let nameIsValid = true; + if (field !== 'name') { + nameIsValid = this.attributeToEdit.name && this.attributeToEdit.name.length > 0; + } + this.onValidationChange.next(isValid && nameIsValid && typeIsValid); + } + + defaultValueChanged() { + this.revalidateDefaultValue(); + } + + /** + * Utility function for UI that converts a simple value to IDropDownOption + * @param val + * @returns {{value: any; label: any}} + */ + toDropDownOption(val: string) { + return { value : val, label: val }; + } + + public isMapUnique = () => { + if (this.attributeToEdit && this.attributeToEdit.type === 'map' && this.attributeToEdit.defaultValue) { + return ValidationUtils.validateUniqueKeys(this.attributeToEdit.defaultValue); + } + return true; + } + + private revalidateDefaultValue() { + this.setDefaultValuePattern(this.attributeToEdit.type); + setTimeout(() => { + if (this.validatedInput) { + this.validatedInput.onKeyPress(this.attributeToEdit.defaultValue); + } }, 250); + } + + private setDefaultValuePattern(valueType: string) { + const selectedSchemaType = this.attributeToEdit.schema.property.type; + this.defaultValuePattern = '.*'; + switch (valueType) { + case 'float': + this.defaultValuePattern = this.validationPatterns.number; + this.defaultValueErrorMessage = this.translateService.translate('VALIDATION_ERROR_TYPE', { type : 'float' }); + break; + case 'integer': + this.defaultValuePattern = this.validationPatterns.integerNoLeadingZero; + this.defaultValueErrorMessage = this.translateService.translate('VALIDATION_ERROR_TYPE', { type : 'integer' }); + break; + case 'list': + if (selectedSchemaType != undefined) { + this.defaultValuePattern = this.listPattern[selectedSchemaType]; + const listTypeStr = `list of ${selectedSchemaType}s (v1, v2, ...) `; + this.defaultValueErrorMessage = this.translateService.translate('VALIDATION_ERROR_TYPE', { type : listTypeStr }); + } + break; + case 'map': + if (selectedSchemaType != undefined) { + this.defaultValuePattern = this.mapPattern[selectedSchemaType]; + const mapTypeStr = `map of ${selectedSchemaType}s (k1:v1, k2:v2, ...)`; + this.defaultValueErrorMessage = this.translateService.translate('VALIDATION_ERROR_TYPE', { type : mapTypeStr }); + } + break; + } + } + +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes-modal.component.spec.ts b/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes-modal.component.spec.ts new file mode 100644 index 0000000000..99aa140dd1 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes-modal.component.spec.ts @@ -0,0 +1,128 @@ +import { NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture } from '@angular/core/testing'; +import { ConfigureFn, configureTests } from '../../../../../jest/test-config.helper'; +import { AttributeModel } from '../../../../models/attributes'; +import { ValidationUtils } from '../../../../utils/validation-utils'; +import { CacheService } from '../../../services/cache.service'; +import { TranslatePipe } from '../../../shared/translator/translate.pipe'; +import { TranslateService } from '../../../shared/translator/translate.service'; +import { AttributeModalComponent } from './attribute-modal.component'; + +describe('attributes modal component', () => { + + let fixture: ComponentFixture; + + // Mocks + let translateServiceMock: Partial; + let cacheServiceMock: Partial; + + const validationPatterns = { + integerNoLeadingZero : 'int_regx', + number : 'number_regx' + }; + + const newAttribute = { + uniqueId: '1', name: 'attr1', description: 'description1', type: 'string', hidden: false, defaultValue: 'val1', schema: null + }; + + beforeEach( + async(() => { + + translateServiceMock = { + translate: jest.fn() + }; + + cacheServiceMock = { + get: jest.fn().mockImplementation((k) => { + return { validationPatterns}; + } ) + }; + + const configure: ConfigureFn = (testBed) => { + testBed.configureTestingModule({ + declarations: [AttributeModalComponent, TranslatePipe], + imports: [], + schemas: [NO_ERRORS_SCHEMA], + providers: [ + {provide: TranslateService, useValue: translateServiceMock}, + {provide: CacheService, useValue: cacheServiceMock}, + ] + }); + }; + + configureTests(configure).then((testBed) => { + fixture = testBed.createComponent(AttributeModalComponent); + }); + }) + ); + + it('test that when hidden is clicked, hidden attribute is set', async () => { + fixture.componentInstance.attributeToEdit = new AttributeModel(); + const hidden = fixture.componentInstance.attributeToEdit.hidden; + fixture.componentInstance.ngOnInit(); + + expect(hidden).toBe(false); + fixture.componentInstance.onHiddenCheckboxClicked(true); + expect(fixture.componentInstance.attributeToEdit.hidden).toBe(true); + }); + + it('test that when type is set to boolean default value is cleared', async () => { + const component = fixture.componentInstance; + component.attributeToEdit = new AttributeModel(); + component.ngOnInit(); + + component.onTypeSelected({ value : 'string', label : 'string'}); + component.attributeToEdit.defaultValue = 'some_value'; + component.onTypeSelected({ value : 'boolean', label : 'boolean'}); + expect(component.attributeToEdit.defaultValue).toBe(''); + + component.onBooleanDefaultValueSelected({ value : 'true', label : 'true'}); + expect(component.attributeToEdit.defaultValue).toBe('true'); + }); + + it('test that when certain type is selected, the correct regex pattern is chosen', async () => { + const component = fixture.componentInstance; + component.attributeToEdit = new AttributeModel(); + component.ngOnInit(); + + // integer + component.onTypeSelected({ value : 'integer', label : 'integer'}); + expect(component.defaultValuePattern).toBe(validationPatterns.integerNoLeadingZero); + + // float + component.onTypeSelected({ value : 'float', label : 'float'}); + expect(component.defaultValuePattern).toBe(validationPatterns.number); + + // list is chosen with no schema, regex pattern is set to default + component.onTypeSelected({ value : 'list', label : 'list'}); + expect(component.defaultValuePattern).toEqual('.*'); + + // schema is set to list of int + component.onEntrySchemaTypeSelected({ value : 'integer', label : 'integer' }); + expect(component.defaultValuePattern).toEqual(ValidationUtils.getPropertyListPatterns().integer); + + // schema is set to list of float + component.onEntrySchemaTypeSelected({ value : 'float', label : 'float' }); + expect(component.defaultValuePattern).toEqual(ValidationUtils.getPropertyListPatterns().float); + + // map is selected (float schema is still selected from previous line) + component.onTypeSelected({ value : 'map', label : 'map'}); + expect(component.defaultValuePattern).toEqual(ValidationUtils.getPropertyMapPatterns().float); + + // change schema type to boolean + component.onEntrySchemaTypeSelected({ value : 'boolean', label : 'boolean' }); + }); + + it('should detect map with non-unique keys', async () => { + const component = fixture.componentInstance; + component.attributeToEdit = new AttributeModel(); + component.ngOnInit(); + expect(component.isMapUnique()).toBe(true); // map is not selected so return true by default + component.onTypeSelected({ value : 'map', label : 'map'}); + component.onEntrySchemaTypeSelected({ value : 'boolean', label : 'boolean' }); + component.attributeToEdit.defaultValue = '"1":true,"2":false'; + expect(component.isMapUnique()).toBe(true); + component.attributeToEdit.defaultValue = '"1":true,"1":false'; + expect(component.isMapUnique()).toBe(false); + }); +}); diff --git a/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes-options.ts b/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes-options.ts new file mode 100644 index 0000000000..2a6924bc5e --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes-options.ts @@ -0,0 +1,60 @@ +import { IDropDownOption } from 'onap-ui-angular/dist/form-elements/dropdown/dropdown-models'; + +export class AttributeOptions { + public static readonly types: IDropDownOption[] = [ + { + label: 'integer', + value: 'integer', + }, + { + label: 'string', + value: 'string', + }, + { + label: 'float', + value: 'float' + }, + { + label: 'boolean', + value: 'boolean' + }, + { + label: 'list', + value: 'list' + }, + { + label: 'map', + value: 'map' + } + ]; + + public static readonly booleanValues: IDropDownOption[] = [ + { + label: 'true', + value: 'true', + }, + { + label: 'false', + value: 'false', + } + ]; + + public static readonly entrySchemaValues: IDropDownOption[] = [ + { + label: 'integer', + value: 'integer', + }, + { + label: 'string', + value: 'string', + }, + { + label: 'float', + value: 'float' + }, + { + label: 'boolean', + value: 'boolean' + } + ]; +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes.component.html b/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes.component.html new file mode 100644 index 0000000000..00a7a5cec0 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes.component.html @@ -0,0 +1,93 @@ + +
+ +
+ + +
+ + + + + +
{{row.description}}
+
+
+ + + + +
+ + {{ row.name }} +
+
+ +
+ + + + {{row.type}} + + + + + + {{row.defaultValue}} + + + + + +
+ + + + +
+
+
+ +
+
\ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes.component.less b/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes.component.less new file mode 100644 index 0000000000..3e91ae4689 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes.component.less @@ -0,0 +1,36 @@ +.action-bar-wrapper { + flex: 0 0 30%; + display: flex; + justify-content: flex-end; + margin-bottom: 10px; +} + +.add-attr-icon{ + cursor: pointer; +} + +.attr-container { + display: flex; + justify-content: space-between; + + .attr-col { + display: flex; + flex-direction: column; + max-width: 275px; + flex-grow: 1; + } + +} + +.attributeType { + margin-bottom: 10px; +} + +sdc-checkbox { + margin-top: 20px; +} + +.actionColumn { + text-align: center; + padding: 5px; +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes.component.spec.ts b/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes.component.spec.ts new file mode 100644 index 0000000000..f676e2b4d9 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes.component.spec.ts @@ -0,0 +1,182 @@ +import { NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture } from '@angular/core/testing'; +import { NgxDatatableModule } from '@swimlane/ngx-datatable'; +import { SdcUiCommon, SdcUiComponents, SdcUiServices } from 'onap-ui-angular'; +import 'rxjs/add/observable/of'; +import { Observable } from 'rxjs/Rx'; +import { ConfigureFn, configureTests } from '../../../../../jest/test-config.helper'; +import { ComponentMetadata } from '../../../../models/component-metadata'; +import { ModalsHandler } from '../../../../utils'; +import { TopologyTemplateService } from '../../../services/component-services/topology-template.service'; +import { TranslateService } from '../../../shared/translator/translate.service'; +import { WorkspaceService } from '../workspace.service'; +import { AttributesComponent } from './attributes.component'; + +describe('attributes component', () => { + + let fixture: ComponentFixture; + + // Mocks + let workspaceServiceMock: Partial; + let topologyTemplateServiceMock: Partial; + let loaderServiceMock: Partial; + let componentMetadataMock: ComponentMetadata; + let modalServiceMock: Partial; + + const mockAttributesList = [ + { uniqueId: '1', name: 'attr1', description: 'description1', type: 'string', hidden: false, defaultValue: 'val1', schema: null }, + { uniqueId : '2', name : 'attr2', description: 'description2', type : 'int', hidden : false, defaultValue : 1, schema : null}, + { uniqueId : '3', name : 'attr3', description: 'description3', type : 'double', hidden : false, defaultValue : 1.0, schema : null}, + { uniqueId : '4', name : 'attr4', description: 'description4', type : 'boolean', hidden : false, defaultValue : true, schema : null}, + ]; + + const newAttribute = { + uniqueId : '5', name : 'attr5', description: 'description5', type : 'string', hidden : false, defaultValue : 'val5', schema : null + }; + const updatedAttribute = { + uniqueId : '2', name : 'attr2', description: 'description_new', type : 'string', hidden : false, defaultValue : 'new_val2', schema : null + }; + const errorAttribute = { + uniqueId : '99', name : 'attr99', description: 'description_error', type : 'string', hidden : false, defaultValue : 'error', schema : null + }; + + beforeEach( + async(() => { + + componentMetadataMock = new ComponentMetadata(); + componentMetadataMock.uniqueId = 'fake'; + componentMetadataMock.componentType = 'VL'; + + topologyTemplateServiceMock = { + getComponentAttributes: jest.fn().mockResolvedValue({ attributes : mockAttributesList }), + addAttributeAsync: jest.fn().mockImplementation( + (compType, cUid, attr) => { + if (attr === errorAttribute) { + return Observable.throwError('add_error').toPromise(); + } else { + return Observable.of(newAttribute).toPromise(); + } + } + ), + updateAttributeAsync: jest.fn().mockImplementation( + (compType, cUid, attr) => { + if (attr === errorAttribute) { + return Observable.throwError('update_error').toPromise(); + } else { + return Observable.of(updatedAttribute).toPromise(); + } + } + ), + deleteAttributeAsync: jest.fn().mockImplementation((cid, ctype, attr) => Observable.of(attr)) + }; + + workspaceServiceMock = { + metadata: componentMetadataMock + }; + + const customModalInstance = { innerModalContent: { instance: { onValidationChange: { subscribe: jest.fn()}}}}; + + modalServiceMock = { + openInfoModal: jest.fn(), + openCustomModal: jest.fn().mockImplementation(() => customModalInstance) + }; + + loaderServiceMock = { + activate: jest.fn(), + deactivate: jest.fn() + }; + + const configure: ConfigureFn = (testBed) => { + testBed.configureTestingModule({ + declarations: [AttributesComponent], + imports: [NgxDatatableModule], + schemas: [NO_ERRORS_SCHEMA], + providers: [ + {provide: WorkspaceService, useValue: workspaceServiceMock}, + {provide: TopologyTemplateService, useValue: topologyTemplateServiceMock}, + {provide: ModalsHandler, useValue: {}}, + {provide: TranslateService, useValue: { translate: jest.fn() }}, + {provide: SdcUiServices.ModalService, useValue: modalServiceMock }, + {provide: SdcUiServices.LoaderService, useValue: loaderServiceMock } + ], + }); + }; + + configureTests(configure).then((testBed) => { + fixture = testBed.createComponent(AttributesComponent); + }); + }) + ); + + it('should see exactly 1 attributes on init', async () => { + await fixture.componentInstance.asyncInitComponent(); + expect(fixture.componentInstance.getAttributes().length).toEqual(4); + }); + + it('should see exactly 5 attributes when adding', async () => { + await fixture.componentInstance.asyncInitComponent(); + expect(fixture.componentInstance.getAttributes().length).toEqual(4); + + await fixture.componentInstance.addOrUpdateAttribute(newAttribute, false); + expect(fixture.componentInstance.getAttributes().length).toEqual(5); + }); + + it('should see exactly 3 attributes when deleting', async () => { + await fixture.componentInstance.asyncInitComponent(); + expect(fixture.componentInstance.getAttributes().length).toEqual(4); + const attrToDelete = mockAttributesList[0]; + expect(fixture.componentInstance.getAttributes().filter((attr) => attr.uniqueId === attrToDelete.uniqueId).length).toEqual(1); + await fixture.componentInstance.deleteAttribute(attrToDelete); + expect(fixture.componentInstance.getAttributes().length).toEqual(3); + expect(fixture.componentInstance.getAttributes().filter((attr) => attr.uniqueId === attrToDelete.uniqueId).length).toEqual(0); + }); + + it('should see updated attribute', async () => { + await fixture.componentInstance.asyncInitComponent(); + + await fixture.componentInstance.addOrUpdateAttribute(updatedAttribute, true); + expect(fixture.componentInstance.getAttributes().length).toEqual(4); + const attribute = fixture.componentInstance.getAttributes().filter( (attr) => { + return attr.uniqueId === updatedAttribute.uniqueId; + })[0]; + expect(attribute.description).toEqual( 'description_new'); + }); + + it('Add fails, make sure loader is deactivated and attribute is not added', async () => { + await fixture.componentInstance.asyncInitComponent(); + const numAttributes = fixture.componentInstance.getAttributes().length; + await fixture.componentInstance.addOrUpdateAttribute(errorAttribute, false); // Add + expect(loaderServiceMock.deactivate).toHaveBeenCalled(); + expect(fixture.componentInstance.getAttributes().length).toEqual(numAttributes); + }); + + it('Update fails, make sure loader is deactivated', async () => { + await fixture.componentInstance.asyncInitComponent(); + const numAttributes = fixture.componentInstance.getAttributes().length; + await fixture.componentInstance.addOrUpdateAttribute(errorAttribute, true); // Add + expect(loaderServiceMock.deactivate).toHaveBeenCalled(); + expect(fixture.componentInstance.getAttributes().length).toEqual(numAttributes); + }); + + it('on delete modal shell be opened', async () => { + await fixture.componentInstance.asyncInitComponent(); + const event = { stopPropagation: jest.fn() }; + fixture.componentInstance.onDeleteAttribute(event, fixture.componentInstance.getAttributes()[0]); + expect(event.stopPropagation).toHaveBeenCalled(); + expect(modalServiceMock.openInfoModal).toHaveBeenCalled(); + }); + + it('on add modal shell be opened', async () => { + await fixture.componentInstance.asyncInitComponent(); + fixture.componentInstance.onAddAttribute(); + expect(modalServiceMock.openCustomModal).toHaveBeenCalled(); + }); + + it('on edit modal shell be opened', async () => { + await fixture.componentInstance.asyncInitComponent(); + const event = { stopPropagation: jest.fn() }; + fixture.componentInstance.onEditAttribute(event, fixture.componentInstance.getAttributes()[0]); + expect(event.stopPropagation).toHaveBeenCalled(); + expect(modalServiceMock.openCustomModal).toHaveBeenCalled(); + }); +}); diff --git a/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes.component.ts b/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes.component.ts new file mode 100644 index 0000000000..bc47f1456b --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes.component.ts @@ -0,0 +1,188 @@ +import { Component, OnInit, ViewChild } from '@angular/core'; +import { Select } from '@ngxs/store'; +import { IAttributeModel } from 'app/models'; +import * as _ from 'lodash'; +import { SdcUiCommon, SdcUiComponents, SdcUiServices } from 'onap-ui-angular'; +import { ModalComponent } from 'onap-ui-angular/dist/modals/modal.component'; +import { AttributeModel } from '../../../../models'; +import { Resource } from '../../../../models'; +import { ModalsHandler } from '../../../../utils'; +import { TopologyTemplateService } from '../../../services/component-services/topology-template.service'; +import { TranslateService } from '../../../shared/translator/translate.service'; +import { WorkspaceState } from '../../../store/states/workspace.state'; +import { WorkspaceService } from '../workspace.service'; +import { AttributeModalComponent } from './attribute-modal.component'; + +@Component({ + selector: 'attributes', + templateUrl: './attributes.component.html', + styleUrls: ['./attributes.component.less', '../../../../../assets/styles/table-style.less'] +}) +export class AttributesComponent implements OnInit { + + @Select(WorkspaceState.isViewOnly) + isViewOnly$: boolean; + + @ViewChild('componentAttributesTable') + private table: any; + + private componentType: string; + private componentUid: string; + + private attributes: IAttributeModel[] = []; + private temp: IAttributeModel[] = []; + private customModalInstance: ModalComponent; + + constructor(private workspaceService: WorkspaceService, + private topologyTemplateService: TopologyTemplateService, + private modalsHandler: ModalsHandler, + private modalService: SdcUiServices.ModalService, + private loaderService: SdcUiServices.LoaderService, + private translateService: TranslateService) { + + this.componentType = this.workspaceService.metadata.componentType; + this.componentUid = this.workspaceService.metadata.uniqueId; + } + + ngOnInit(): void { + this.asyncInitComponent(); + } + + async asyncInitComponent() { + this.loaderService.activate(); + const response = await this.topologyTemplateService.getComponentAttributes(this.componentType, this.componentUid); + this.attributes = response.attributes; + this.temp = [...response.attributes]; + this.loaderService.deactivate(); + } + + getAttributes(): IAttributeModel[] { + return this.attributes; + } + + addOrUpdateAttribute = async (attribute: AttributeModel, isEdit: boolean) => { + this.loaderService.activate(); + let attributeFromServer: AttributeModel; + this.temp = [...this.attributes]; + + const deactivateLoader = () => { + this.loaderService.deactivate(); + return undefined; + }; + + if (isEdit) { + attributeFromServer = await this.topologyTemplateService + .updateAttributeAsync(this.componentType, this.componentUid, attribute) + .catch(deactivateLoader); + if (attributeFromServer) { + const indexOfUpdatedAttribute = _.findIndex(this.temp, (e) => e.uniqueId === attributeFromServer.uniqueId); + this.temp[indexOfUpdatedAttribute] = attributeFromServer; + } + } else { + attributeFromServer = await this.topologyTemplateService + .addAttributeAsync(this.componentType, this.componentUid, attribute) + .catch(deactivateLoader); + if (attributeFromServer) { + this.temp.push(attributeFromServer); + } + } + this.attributes = this.temp; + this.loaderService.deactivate(); + } + + deleteAttribute = async (attributeToDelete: AttributeModel) => { + this.loaderService.activate(); + this.temp = [...this.attributes]; + const res = await this.topologyTemplateService.deleteAttributeAsync(this.componentType, this.componentUid, attributeToDelete); + _.remove(this.temp, (attr) => attr.uniqueId === attributeToDelete.uniqueId); + this.attributes = this.temp; + this.loaderService.deactivate(); + }; + + openAddEditModal(selectedRow: AttributeModel, isEdit: boolean) { + const component = new Resource(undefined, undefined, undefined); + component.componentType = this.componentType; + component.uniqueId = this.componentUid; + + const title: string = this.translateService.translate('ATTRIBUTE_DETAILS_MODAL_TITLE'); + const attributeModalConfig = { + title, + size: 'md', + type: SdcUiCommon.ModalType.custom, + buttons: [ + { + id: 'save', + text: 'Save', + // spinner_position: Placement.left, + size: 'sm', + callback: () => this.modalCallBack(isEdit), + closeModal: true, + disabled: false, + } + ] as SdcUiCommon.IModalButtonComponent[] + }; + + this.customModalInstance = this.modalService.openCustomModal(attributeModalConfig, AttributeModalComponent, { attributeToEdit: selectedRow }); + this.customModalInstance.innerModalContent.instance. + onValidationChange.subscribe((isValid) => this.customModalInstance.getButtonById('save').disabled = !isValid); + } + + /*********************** + * Call Backs from UI * + ***********************/ + + /** + * Called when 'Add' is clicked + */ + onAddAttribute() { + this.openAddEditModal(new AttributeModel(), false); + } + + /** + * Called when 'Edit' button is clicked + */ + onEditAttribute(event, row) { + event.stopPropagation(); + + const attributeToEdit: AttributeModel = new AttributeModel(row); + this.openAddEditModal(attributeToEdit, true); + } + + /** + * Called when 'Delete' button is clicked + */ + onDeleteAttribute(event, row: AttributeModel) { + event.stopPropagation(); + const onOk = () => { + this.deleteAttribute(row); + }; + + const title: string = this.translateService.translate('ATTRIBUTE_VIEW_DELETE_MODAL_TITLE'); + const message: string = this.translateService.translate('ATTRIBUTE_VIEW_DELETE_MODAL_TEXT'); + const okButton = new SdcUiComponents.ModalButtonComponent(); + okButton.testId = 'OK'; + okButton.text = 'OK'; + okButton.type = SdcUiCommon.ButtonType.info; + okButton.closeModal = true; + okButton.callback = onOk; + + this.modalService.openInfoModal(title, message, 'delete-modal', [okButton]); + } + + onExpandRow(event) { + if (event.type === 'click') { + this.table.rowDetail.toggleExpandRow(event.row); + } + } + + /** + * Callback from Modal after "Save" is clicked + * + * @param {boolean} isEdit - Whether modal is edit or add attribute + */ + modalCallBack = (isEdit: boolean) => { + const attribute: AttributeModel = this.customModalInstance.innerModalContent.instance.attributeToEdit; + this.addOrUpdateAttribute(attribute, isEdit); + } + +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes.module.ts b/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes.module.ts new file mode 100644 index 0000000000..5abb952e37 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/attributes/attributes.module.ts @@ -0,0 +1,32 @@ +import { CommonModule } from '@angular/common'; +import { NgModule } from '@angular/core'; +import { SdcUiComponentsModule } from 'onap-ui-angular'; +import { GlobalPipesModule } from '../../../pipes/global-pipes.module'; +import { AttributesComponent } from './attributes.component'; +import { NgxDatatableModule } from '@swimlane/ngx-datatable'; +import { TopologyTemplateService } from '../../../services/component-services/topology-template.service'; +import { AttributeModalComponent } from './attribute-modal.component'; +import { TranslateModule } from '../../../shared/translator/translate.module'; + +@NgModule({ + declarations: [ + AttributesComponent, + AttributeModalComponent + ], + imports: [ + CommonModule, + SdcUiComponentsModule, + GlobalPipesModule, + NgxDatatableModule, + TranslateModule + ], + exports: [ + AttributesComponent + ], + entryComponents: [ + AttributesComponent, AttributeModalComponent + ], + providers: [TopologyTemplateService] +}) +export class AttributesModule { +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/__snapshots__/deployment-artifacts-page.spec.ts.snap b/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/__snapshots__/deployment-artifacts-page.spec.ts.snap new file mode 100644 index 0000000000..b53674497c --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/__snapshots__/deployment-artifacts-page.spec.ts.snap @@ -0,0 +1,24 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`deployment artifacts page should match current snapshot of informational artifact pages component 1`] = ` + + + +`; diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/deployment-artifacts-page.component.html b/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/deployment-artifacts-page.component.html new file mode 100644 index 0000000000..35592d846a --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/deployment-artifacts-page.component.html @@ -0,0 +1,73 @@ +
+ + + + +
+
+
+ {{row.artifactDisplayName}} + + + +
+
+ + + {{row.artifactType}} + + exactly 2 tosca artifacts + + + {{ row.artifactVersion }} + + + + + {{ row.artifactUUID }} + + + + +
+ + + + + + +
+
+
+ + + + + + +
+
diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/deployment-artifacts-page.component.less b/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/deployment-artifacts-page.component.less new file mode 100644 index 0000000000..22ceb96653 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/deployment-artifacts-page.component.less @@ -0,0 +1,55 @@ +.deployment-artifact-page { + + + .env-artifact-container { + margin-left: -25px; + margin-top: -21px; + padding-left: 10px; + position: absolute; + background-color: white; + .env-artifact { + border-left: 1px #848586 solid; + height: 33px; + + border-top: 1px #848586 solid; + border-bottom: 1px #848586 solid; + width: 10px; + float: left; + + } + } + .add-artifact-btn { + display: flex; + cursor: pointer; + justify-content: flex-end; + margin-bottom: 10px; + } + .download-artifact-button { + display: flex; + justify-content: center; + + .action-icon { + margin-right: 10px; + } + } + + .table-footer-container { + display: flex; + align-items: center; + width: 100%; + justify-content: center; + margin: 20px 0px; + } +} + +:host ::ng-deep { + + .ngx-datatable { + //border: 1px solid red; + .datatable-body-cell { + .info { + float: right; + } + } + } +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/deployment-artifacts-page.component.ts b/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/deployment-artifacts-page.component.ts new file mode 100644 index 0000000000..53b21b34b6 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/deployment-artifacts-page.component.ts @@ -0,0 +1,155 @@ +import { Component, OnInit, ViewChild } from '@angular/core'; +import { Select, Store } from '@ngxs/store'; +import { ArtifactModel } from 'app/models'; +import * as _ from 'lodash'; +import { SdcUiCommon, SdcUiComponents, SdcUiServices } from 'onap-ui-angular'; +import { Observable } from 'rxjs/index'; +import { map } from 'rxjs/operators'; +import { GabConfig } from '../../../../models/gab-config'; +import { PathsAndNamesDefinition } from '../../../../models/paths-and-names'; +import { GenericArtifactBrowserComponent } from '../../../../ng2/components/logic/generic-artifact-browser/generic-artifact-browser.component'; +import { ArtifactGroupType, ArtifactType } from '../../../../utils/constants'; +import { ArtifactsService } from '../../../components/forms/artifacts-form/artifacts.service'; +import { PopoverContentComponent } from '../../../components/ui/popover/popover-content.component'; +import { CacheService } from '../../../services/cache.service'; +import { TranslateService } from '../../../shared/translator/translate.service'; +import { GetArtifactsByTypeAction } from '../../../store/actions/artifacts.action'; +import { ArtifactsState } from '../../../store/states/artifacts.state'; +import { WorkspaceState, WorkspaceStateModel } from '../../../store/states/workspace.state'; +import { WorkspaceService } from '../workspace.service'; +import { ModalService } from 'app/ng2/services/modal.service'; + +export interface IPoint { + x: number; + y: number; +} + +@Component({ + selector: 'deployment-artifact-page', + templateUrl: './deployment-artifacts-page.component.html', + styleUrls: ['./deployment-artifacts-page.component.less', '../../../../../assets/styles/table-style.less'] +}) +export class DeploymentArtifactsPageComponent implements OnInit { + + public componentId: string; + public componentType: string; + public deploymentArtifacts$: Observable; + public isComponentInstanceSelected: boolean; + + @Select(WorkspaceState) workspaceState$: Observable; + @ViewChild('informationArtifactsTable') table: any; + @ViewChild('popoverForm') popoverContentComponent: PopoverContentComponent; + + constructor(private workspaceService: WorkspaceService, + private artifactsService: ArtifactsService, + private store: Store, + private popoverService: SdcUiServices.PopoverService, + private cacheService: CacheService, + private modalService: SdcUiServices.ModalService, + private translateService: TranslateService) { + } + + private getEnvArtifact = (heatArtifact: ArtifactModel, artifacts: ArtifactModel[]): ArtifactModel => { + return _.find(artifacts, (item: ArtifactModel) => { + return item.generatedFromId === heatArtifact.uniqueId; + }); + }; + + // we need to sort the artifact in a way that the env artifact is always under the artifact he is connected to- this is cause of the way the ngx databale work + private sortArtifacts = ((artifacts) => { + const sortedArtifacts = []; + _.forEach(artifacts, (artifact: ArtifactModel): void => { + const envArtifact = this.getEnvArtifact(artifact, artifacts); + if (!artifact.generatedFromId) { + sortedArtifacts.push(artifact); + } + if (envArtifact) { + sortedArtifacts.push(envArtifact); + } + }); + return sortedArtifacts; + }) + + ngOnInit(): void { + this.componentId = this.workspaceService.metadata.uniqueId; + this.componentType = this.workspaceService.metadata.componentType; + + this.store.dispatch(new GetArtifactsByTypeAction({ + componentType: this.componentType, + componentId: this.componentId, + artifactType: ArtifactGroupType.DEPLOYMENT + })); + this.deploymentArtifacts$ = this.store.select(ArtifactsState.getArtifactsByType).pipe(map((filterFn) => filterFn(ArtifactType.DEPLOYMENT))).pipe(map(artifacts => { + return this.sortArtifacts(artifacts); + })); + } + + onActivate(event) { + if (event.type === 'click') { + this.table.rowDetail.toggleExpandRow(event.row); + } + } + + public addOrUpdateArtifact = (artifact: ArtifactModel, isViewOnly: boolean) => { + this.artifactsService.openArtifactModal(this.componentId, this.componentType, artifact, ArtifactGroupType.DEPLOYMENT, isViewOnly); + } + + public deleteArtifact = (artifactToDelete) => { + this.artifactsService.deleteArtifact(this.componentType, this.componentId, artifactToDelete); + } + + private openPopOver = (title: string, content: string, positionOnPage: IPoint, location: string) => { + this.popoverService.createPopOver(title, content, positionOnPage, location); + } + + public updateEnvParams = (artifact: ArtifactModel, isViewOnly: boolean) => { + this.artifactsService.openUpdateEnvParams(this.componentType, this.componentId, artifact ); + } + + private openGenericArtifactBrowserModal = (artifact: ArtifactModel): void => { + const titleStr = 'Generic Artifact Browser'; + const modalConfig = { + size: 'sdc-xl', + title: titleStr, + type: SdcUiCommon.ModalType.custom, + buttons: [{ + id: 'closeGABButton', + text: 'Close', + size: 'sm', + closeModal: true + }] as SdcUiCommon.IModalButtonComponent[] + }; + + const uiConfiguration: any = this.cacheService.get('UIConfiguration'); + let noConfig: boolean = false; + let pathsandnamesArr: PathsAndNamesDefinition[] = []; + + if (typeof uiConfiguration.gab === 'undefined') { + noConfig = true; + } else { + const gabConfig: GabConfig = uiConfiguration.gab + .find((config) => config.artifactType === artifact.artifactType); + if (typeof gabConfig === 'undefined') { + noConfig = true; + } else { + pathsandnamesArr = gabConfig.pathsAndNamesDefinitions; + } + } + + + if (noConfig) { + const msg = this.translateService.translate('DEPLOYMENT_ARTIFACT_GAB_NO_CONFIG'); + this.modalService.openAlertModal(titleStr, msg); + } + + const modalInputs = { + pathsandnames: pathsandnamesArr, + artifactid: artifact.esId, + resourceid: this.componentId + }; + + this.modalService.openCustomModal(modalConfig, GenericArtifactBrowserComponent, modalInputs); + + } + +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/deployment-artifacts-page.module.ts b/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/deployment-artifacts-page.module.ts new file mode 100644 index 0000000000..398e9d3f4d --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/deployment-artifacts-page.module.ts @@ -0,0 +1,35 @@ +import {CommonModule} from "@angular/common"; +import {NgModule} from "@angular/core"; +import {SdcUiComponentsModule} from "onap-ui-angular"; +import {NgxDatatableModule} from "@swimlane/ngx-datatable"; +import {UiElementsModule} from "../../../components/ui/ui-elements.module"; +import {ArtifactFormModule} from "../../../components/forms/artifacts-form/artifact-form.module"; +import {ArtifactsService} from "../../../components/forms/artifacts-form/artifacts.service"; +import {DeploymentArtifactsPageComponent} from "./deployment-artifacts-page.component"; +import {TranslatePipe} from "../../../shared/translator/translate.pipe"; +import {TranslateModule} from "../../../shared/translator/translate.module"; +import {GenericArtifactBrowserModule} from "../../../components/logic/generic-artifact-browser/generic-artifact-browser.module"; + +@NgModule({ + declarations: [ + DeploymentArtifactsPageComponent + ], + imports: [ + TranslateModule, + CommonModule, + SdcUiComponentsModule, + NgxDatatableModule, + UiElementsModule, + ArtifactFormModule, + GenericArtifactBrowserModule + ], + exports: [ + DeploymentArtifactsPageComponent + ], + entryComponents: [ + DeploymentArtifactsPageComponent + ], + providers:[ArtifactsService] +}) +export class DeploymentArtifactsPageModule { +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/deployment-artifacts-page.spec.ts b/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/deployment-artifacts-page.spec.ts new file mode 100644 index 0000000000..056efdc5d4 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment-artifacts/deployment-artifacts-page.spec.ts @@ -0,0 +1,86 @@ +// import ' rxjs/add/observable/of'; +import { NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture } from '@angular/core/testing'; +import { NgxsModule, Store } from '@ngxs/store'; +import { NgxDatatableModule } from '@swimlane/ngx-datatable'; +import { SdcUiServices } from 'onap-ui-angular'; +import { Observable } from 'rxjs/Observable'; +import { deploymentArtifactMock } from '../../../../../jest/mocks/artifacts-mock'; +import { ConfigureFn, configureTests } from '../../../../../jest/test-config.helper'; +import { ComponentMetadata } from '../../../../models/component-metadata'; +import { ArtifactsService } from '../../../components/forms/artifacts-form/artifacts.service'; +import { CacheService } from '../../../services/cache.service'; +import { TopologyTemplateService } from '../../../services/component-services/topology-template.service'; +import { TranslateModule } from '../../../shared/translator/translate.module'; +import { TranslateService } from '../../../shared/translator/translate.service'; +import { ArtifactsState } from '../../../store/states/artifacts.state'; +import { WorkspaceService } from '../workspace.service'; +import { DeploymentArtifactsPageComponent } from './deployment-artifacts-page.component'; +import {ModalService} from "../../../services/modal.service"; + +describe('deployment artifacts page', () => { + + let fixture: ComponentFixture; + let topologyTemplateServiceMock: Partial; + let workspaceServiceMock: Partial; + let loaderServiceMock: Partial; + let store: Store; + + beforeEach( + async(() => { + + topologyTemplateServiceMock = { + getArtifactsByType: jest.fn().mockImplementation((componentType, id, artifactType) => Observable.of(deploymentArtifactMock)) + }; + workspaceServiceMock = { + metadata: { + uniqueId: 'service_unique_id', + componentType: 'SERVICE' + } + } + + loaderServiceMock = { + activate: jest.fn(), + deactivate: jest.fn() + } + const configure: ConfigureFn = (testBed) => { + testBed.configureTestingModule({ + declarations: [DeploymentArtifactsPageComponent], + imports: [NgxDatatableModule, TranslateModule, NgxsModule.forRoot([ArtifactsState])], + schemas: [NO_ERRORS_SCHEMA], + providers: [ + {provide: WorkspaceService, useValue: workspaceServiceMock}, + {provide: TopologyTemplateService, useValue: topologyTemplateServiceMock}, + {provide: SdcUiServices.LoaderService, useValue: loaderServiceMock}, + {provide: ArtifactsService, useValue: {}}, + {provide: SdcUiServices.PopoverService, useValue: {}}, + {provide: CacheService, useValue: {}}, + {provide: SdcUiServices.ModalService, useValue: {}}, + {provide: ModalService, useValue: {}}, + {provide: TranslateService, useValue: {}} + ], + }); + }; + + configureTests(configure).then((testBed) => { + fixture = testBed.createComponent(DeploymentArtifactsPageComponent); + store = testBed.get(Store); + }); + }) + ); + + it('should match current snapshot of informational artifact pages component', () => { + expect(fixture).toMatchSnapshot(); + }); + + it('should see exactly 2 tosca artifacts', () => { + fixture.componentInstance.ngOnInit(); + fixture.componentInstance.deploymentArtifacts$.subscribe((artifacts) => { + expect(artifacts.length).toEqual(8); + }) + store.selectOnce((state) => state.artifacts.deploymentArtifacts).subscribe((artifacts) => { + expect(artifacts.length).toEqual(8); + }); + }); + +}); diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment/deployment-page.component.html b/catalog-ui/src/app/ng2/pages/workspace/deployment/deployment-page.component.html new file mode 100644 index 0000000000..885277217d --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment/deployment-page.component.html @@ -0,0 +1,11 @@ +
+ + + + + + + + +
\ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment/deployment-page.component.less b/catalog-ui/src/app/ng2/pages/workspace/deployment/deployment-page.component.less new file mode 100644 index 0000000000..4b7a1e7e9f --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment/deployment-page.component.less @@ -0,0 +1,24 @@ +@import './../../../../../assets/styles/variables.less'; +@import './../../../../../assets/styles/override.less'; +.deployment-page { + width: 100%; + height: 100%; + + /deep/ .sdc-tabs { + height: 100%; + } + /deep/ .sdc-tabs-list { + position: absolute; + top: 22px; + right: 303px; + background-color: @sdcui_color_silver; + + svg-icon-label { + vertical-align: middle; + } + } + /deep/ .sdc-tab-content { + height: 100%; + } +} + diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment/deployment-page.component.ts b/catalog-ui/src/app/ng2/pages/workspace/deployment/deployment-page.component.ts new file mode 100644 index 0000000000..12bd5369c7 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment/deployment-page.component.ts @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +import {Component} from "@angular/core"; +import {HierarchyTabComponent} from "./panel/panel-tabs/hierarchy-tab/hierarchy-tab.component"; +import {ComponentGenericResponse} from "../../../services/responses/component-generic-response"; +import {TopologyTemplateService} from "../../../services/component-services/topology-template.service"; +import {WorkspaceService} from "../workspace.service"; +import {Module} from "app/models"; +import {SdcUiServices} from "onap-ui-angular"; +import {Select} from "@ngxs/store"; +import {WorkspaceState} from "../../../store/states/workspace.state"; +import {DeploymentGraphService} from "../../composition/deployment/deployment-graph.service"; + +const tabs = + { + hierarchyTab: { + titleIcon: 'composition-o', + component: HierarchyTabComponent, + input: {}, + isActive: true, + tooltipText: 'Hierarchy' + } + }; + +@Component({ + selector: 'deployment-page', + templateUrl: './deployment-page.component.html', + styleUrls: ['deployment-page.component.less'] +}) + +export class DeploymentPageComponent { + public tabs: Array; + public resourceType: string; + public modules: Array; + public isDataAvailable: boolean; + + @Select(WorkspaceState.isViewOnly) isViewOnly$: boolean; + + constructor(private topologyTemplateService: TopologyTemplateService, + private workspaceService: WorkspaceService, + private deploymentService: DeploymentGraphService, + private loaderService: SdcUiServices.LoaderService) { + this.tabs = []; + this.isDataAvailable = false; + } + + ngOnInit(): void { + this.topologyTemplateService.getDeploymentGraphData(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId).subscribe((response: ComponentGenericResponse) => { + this.deploymentService.componentInstances = response.componentInstances; + this.deploymentService.componentInstancesRelations = response.componentInstancesRelations; + this.deploymentService.modules = response.modules; + this.isDataAvailable = true; + this.loaderService.deactivate(); + }); + + this.loaderService.activate(); + this.resourceType = this.workspaceService.getMetadataType(); + this.tabs.push(tabs.hierarchyTab); + } +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment/deployment-page.module.ts b/catalog-ui/src/app/ng2/pages/workspace/deployment/deployment-page.module.ts new file mode 100644 index 0000000000..3635e8f2cf --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment/deployment-page.module.ts @@ -0,0 +1,30 @@ +/** + * Created by ob0695 on 6/4/2018. + */ +import {NgModule} from "@angular/core"; +import {CommonModule} from "@angular/common"; +import {DeploymentPageComponent} from "./deployment-page.component"; +import {SdcUiComponentsModule} from "onap-ui-angular"; +import {UiElementsModule} from "../../../components/ui/ui-elements.module"; +import {TranslateModule} from "../../../shared/translator/translate.module"; +import {GlobalPipesModule} from "../../../pipes/global-pipes.module"; +import {HierarchyTabModule} from "./panel/panel-tabs/hierarchy-tab/hierarchy-tab.module"; +import {DeploymentGraphService} from "../../composition/deployment/deployment-graph.service"; +import {DeploymentGraphModule} from "../../composition/deployment/deployment-graph.module"; + +@NgModule({ + declarations: [DeploymentPageComponent], + imports: [CommonModule, + DeploymentGraphModule, + SdcUiComponentsModule, + UiElementsModule, + TranslateModule, + GlobalPipesModule, + HierarchyTabModule + ], + exports: [DeploymentPageComponent], + entryComponents: [DeploymentPageComponent], + providers: [DeploymentGraphService] +}) +export class DeploymentPageModule { +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/edit-module-name/edit-module-name.component.html b/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/edit-module-name/edit-module-name.component.html new file mode 100644 index 0000000000..d5b9d9e9b2 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/edit-module-name/edit-module-name.component.html @@ -0,0 +1,29 @@ +
+
{{selectModule.vfInstanceName}}
+
+ + + + + +
+
{{selectModule.moduleName}}
+ + + + +
\ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/edit-module-name/edit-module-name.component.less b/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/edit-module-name/edit-module-name.component.less new file mode 100644 index 0000000000..721ad53bc3 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/edit-module-name/edit-module-name.component.less @@ -0,0 +1,20 @@ +.edit-module-name-btn{ + float:right; + margin-left: 10px; + margin-bottom: 20px; +} +.save-button { + margin-left: 30px; +} +.cancel-button { + margin-left: 20px; +} +.edit-module-name-heatName { + margin-bottom: 15px; +} +.edit-module-name-label { + text-overflow: ellipsis; + display: block; + white-space: nowrap; + margin-bottom: 10px; +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/edit-module-name/edit-module-name.component.ts b/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/edit-module-name/edit-module-name.component.ts new file mode 100644 index 0000000000..819182c75f --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/edit-module-name/edit-module-name.component.ts @@ -0,0 +1,24 @@ +import { Component, Input, Output, OnInit } from "@angular/core"; +import { EventEmitter } from "@angular/core"; +import { DisplayModule } from "../../../../../../../models/modules/base-module"; +import { ValidationConfiguration } from "../../../../../../../models/validation-config"; + +@Component({ + selector: 'edit-module-name', + templateUrl: './edit-module-name.component.html', + styleUrls: ['edit-module-name.component.less'] +}) +export class EditModuleName implements OnInit{ + @Input() selectModule:DisplayModule; + @Output() clickButtonEvent: EventEmitter = new EventEmitter(); + private pattern = ValidationConfiguration.validation.validationPatterns.stringOrEmpty; + private originalName: string; + constructor(){} + public ngOnInit(): void { + this.originalName = this.selectModule.heatName; + } + + private clickButton(saveOrCancel: boolean) : void { + this.clickButtonEvent.emit(saveOrCancel ? this.selectModule.heatName : null); + } +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/hierarchy-tab/hierarchy-tab.component.html b/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/hierarchy-tab/hierarchy-tab.component.html new file mode 100644 index 0000000000..7c0e60b814 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/hierarchy-tab/hierarchy-tab.component.html @@ -0,0 +1,119 @@ +
+ +
{{'DEPLOYMENT_TAB_TITLE' | translate }}
+
+
+
+
{{topologyTemplateName}}
+
+ +
+
{{memberId}}
+
+
+
+
+
+ + +
+
+ +
+ +
+
{{memberId}}
+
+
+
+
+
+
+
+ + +
+
+
+
{{selectedModule.name}}
+
+ +
+
+
+
Module ID:
+
{{selectedModule.groupUUID}}
+
+
+
Customization ID:
+
{{selectedModule.customizationUUID}}
+
+
+
Invariant UUID:
+
{{selectedModule.invariantUUID}}
+
+
+
Version:
+
{{selectedModule.version}}
+
+
+
IsBase:
+
{{selectedModule.isBase}}
+
+ +
+ +
+
+
+ {{property.name}} +
+
Type: {{property.type}}
+
+ Value: {{property.value}}
+
+
+
+ +
+
+
+
{{artifact.artifactName}}
+
UUID: {{artifact.artifactUUID}}
+
+ Version: {{artifact.artifactVersion}}
+
+
+
+
+
+
+
diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/hierarchy-tab/hierarchy-tab.component.less b/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/hierarchy-tab/hierarchy-tab.component.less new file mode 100644 index 0000000000..269ca0aee0 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/hierarchy-tab/hierarchy-tab.component.less @@ -0,0 +1,222 @@ +@import './../../../../../../../../assets/styles/variables.less'; +.sdc-hierarchy-tab { + padding: 15px 0 0 0; + background-color: #f8f8f8; + height: 100%; + box-shadow: 0.3px 1px 3px rgba(24, 24, 25, 0.42); + display: flex; + flex-flow: column; + + .sdc-hierarchy-tab-title { + color: @main_color_a; + padding: 0 0 15px 20px; + border-bottom: 1px solid #d2d2d2; + } + + .sdc-hierarchy-tab-sub-title { + color: @main_color_a; + padding: 15px 20px 15px 20px; + } + + .scroll-module-list { + overflow-y: auto; + display: flex; + height: 100%; + flex-direction: column; + } + + /deep/ .expand-collapse-container { + margin-bottom: 0; + + .sdc-accordion-header { + white-space: nowrap; + line-height: 22px; + background-color: @tlv_color_u; + padding: 8px 20px 8px 8px; + box-shadow: inset 0px -1px 0px 0px rgba(255, 255, 255, 0.7); + height: 40px; + + .title { + overflow: hidden; + text-overflow: ellipsis; + max-width: 215px; + } + } + + .sdc-accordion-body.open { + padding: 0 0 5px 0; + } + + .sdc-accordion-header:hover { + background-color: @main_color_o; + } + + &.outer-container { + .sdc-accordion-body { + padding-left: 0; + } + } + + &.inner-container { + margin-bottom: 0; + + .sdc-accordion-header { + padding: 8px 20px 8px 30px; + background-color: @tlv_color_t + } + } + } + + sdc-accordion.selected { + /deep/ .expand-collapse-container { + .sdc-accordion-header { + background-color: @main_color_a; + color: @main_color_p; + + .svg-icon { + fill: @main_color_p; + } + } + } + } + + .expand-collapse-sub-title { + max-width: 225px; + display: inline-block; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + padding: 10px 0 0 33px; + } + + .expand-collapse-content { + .expand-collapse-title { + padding: 0 10px 0 30px; + } + } + + .module-data-container { + width: 100%; + overflow-y: overlay; + background-color: @tlv_color_v; + border: 1px solid @main_color_a; + border-top: 4px solid @main_color_a; + box-shadow: 0.3px 1px 2px rgba(24, 24, 25, 0.32); + .module-data { + color: @main_color_a; + padding: 10px 0 10px 0; + margin: 0 20px 0 20px; + + .selected-module-property-header { + font-weight: bold; + } + + .selected-module-property-value { + font-family: @font-opensans-regular; + + &.small-font { + font-size: 12px; + } + } + + .module-name-container { + + display: flex; + flex-direction: row; + + .module-name { + font-size: 14px; + width: 75%; + max-width: 240px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .edit-name-container { + float: right; + border-left: 1px solid @main_color_a; + height: 20px; + padding-left: 12px; + + svg-icon { + padding-top: 3px; + fill: @main_color_s; + + &.hand-pointer { + cursor: pointer; + } + + } + } + } + } + + .selected-module-property-container { + flex-direction: row; + display: flex; + + .selected-module-property-value { + text-indent: 2px; + } + } + + /deep/ .expand-collapse-module-data-container { + margin-bottom: 0; + + .sdc-accordion-header { + white-space: nowrap; + line-height: 22px; + padding: 8px 20px 8px 16px; + height: 40px; + background-color: @tlv_color_w; + color: @main_color_l; + border-top: 1px solid @main_color_a; + border-bottom: 1px solid @main_color_a; + width: 100%; + } + + } + + .module-data-list-item { + padding-bottom: 10px; + margin: 0 20px 0 20px; + + .artifact-list-item { + color: @main_color_m; + } + + .module-data-list-item-value { + width: 100%; + max-width: 240px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + + &.artifact-info { + font-family: @font-opensans-regular; + font-size: 12px; + } + + &.property-name { + font-weight: 400; + color: @main_color_a; + + .hand-pointer { + cursor: pointer; + } + } + + &.property-info { + color: @func_color_s; + font-family: @font-opensans-regular; + } + } + } + } +} + +.modules-list { + overflow-y: overlay; + flex-grow: 1; +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/hierarchy-tab/hierarchy-tab.component.spec.ts b/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/hierarchy-tab/hierarchy-tab.component.spec.ts new file mode 100644 index 0000000000..ab88867cc0 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/hierarchy-tab/hierarchy-tab.component.spec.ts @@ -0,0 +1,133 @@ +import {async, ComponentFixture} from "@angular/core/testing"; +import {HierarchyTabComponent} from "./hierarchy-tab.component"; +import {ConfigureFn, configureTests} from "../../../../../../../../jest/test-config.helper"; +import {NO_ERRORS_SCHEMA} from "@angular/core"; +import {TranslateModule} from "../../../../../../shared/translator/translate.module"; +import {TopologyTemplateService} from "../../../../../../services/component-services/topology-template.service"; +import {WorkspaceService} from "../../../../workspace.service"; +import {ModulesService} from "../../../../../../services/modules.service"; +import {GlobalPipesModule} from "../../../../../../pipes/global-pipes.module"; +import {TranslateService} from "../../../../../../shared/translator/translate.service"; +import {ModalsHandler} from "../../../../../../../utils/modals-handler"; +import {ComponentFactory} from "../../../../../../../utils/component-factory"; +import {NgxsModule} from "@ngxs/store"; +import { SdcUiServices } from "onap-ui-angular"; +import {Observable} from "rxjs"; +import {DisplayModule, Module} from "../../../../../../../models/modules/base-module"; +import {DeploymentGraphService} from "../../../../../composition/deployment/deployment-graph.service"; +import {ComponentMetadata} from "../../../../../../../models/component-metadata"; + +describe('HierarchyTabComponent', () => { + + let fixture: ComponentFixture; + let workspaceService: Partial; + let popoverServiceMock: Partial; + let modulesServiceMock: Partial; + + let editModuleNameInstanceMock = {innerPopoverContent:{instance: { clickButtonEvent: Observable.of("new heat name")}}, + closePopover: jest.fn()}; + let eventMock = {x: 1650, y: 350}; + let moduleMock: Array = [{name: "NewVf2..base_vepdg..module-0", uniqueId: '1'}]; + let selectedModuleMock: DisplayModule = {name: "NewVf2..base_vepdg..module-0", vfInstanceName: "NewVf2", moduleName:"module-0", + heatName: "base_vepdg", uniqueId: '1', updateName: jest.fn().mockImplementation(() => { + selectedModuleMock.name = selectedModuleMock.vfInstanceName + '..' + selectedModuleMock.heatName + '..' + + selectedModuleMock.moduleName;})} + let updateSelectedModuleMock = () => { + selectedModuleMock.heatName = "base_vepdg"; + selectedModuleMock.name = "NewVf2..base_vepdg..module-0"; + fixture.componentInstance.selectedModule = selectedModuleMock; + fixture.componentInstance.modules = moduleMock; + } + beforeEach( + async(() => { + + workspaceService ={ + metadata: { + name: '', + componentType: '' + } + } + popoverServiceMock = { + createPopOverWithInnerComponent: jest.fn().mockImplementation(() => {return editModuleNameInstanceMock}) + } + modulesServiceMock = { + updateModuleMetadata: jest.fn().mockReturnValue(Observable.of({})) + } + + const configure: ConfigureFn = testBed => { + testBed.configureTestingModule({ + declarations: [HierarchyTabComponent], + schemas: [NO_ERRORS_SCHEMA], + imports: [TranslateModule, NgxsModule.forRoot([]), GlobalPipesModule], + providers: [ + {provide: DeploymentGraphService, useValue: {}}, + {provide: ComponentFactory, useValue: {}}, + {provide: TopologyTemplateService, useValue: {}}, + {provide: WorkspaceService, useValue: workspaceService}, + {provide: ModulesService, useValue: modulesServiceMock}, + {provide: TranslateService, useValue: {}}, + {provide: ModalsHandler, useValue: {}}, + {provide: SdcUiServices.PopoverService, useValue: popoverServiceMock} + ] + }); + }; + + configureTests(configure).then(testBed => { + fixture = testBed.createComponent(HierarchyTabComponent); + }); + }) + ); + + it('expected heirarchy component to be defined', () => { + expect(fixture).toBeDefined(); + }); + + it('Update heat name and name sucessfully', () => { + updateSelectedModuleMock(); + fixture.componentInstance.openEditModuleNamePopup(eventMock); + expect(fixture.componentInstance.selectedModule.updateName).toHaveBeenCalled(); + expect(modulesServiceMock.updateModuleMetadata).toHaveBeenCalled(); + expect(fixture.componentInstance.selectedModule.name).toEqual('NewVf2..new heat name..module-0'); + expect(fixture.componentInstance.modules[0].name).toEqual('NewVf2..new heat name..module-0'); + expect(fixture.componentInstance.selectedModule.heatName).toEqual('new heat name'); + }) + it('Try to update heat name and name and get error from server', () => { + updateSelectedModuleMock(); + modulesServiceMock.updateModuleMetadata.mockImplementation(() => Observable.throwError({})); + fixture.componentInstance.openEditModuleNamePopup(eventMock); + expect(fixture.componentInstance.selectedModule.updateName).toHaveBeenCalled(); + expect(modulesServiceMock.updateModuleMetadata).toHaveBeenCalled(); + expect(fixture.componentInstance.modules[0].name).toEqual('NewVf2..base_vepdg..module-0'); + expect(fixture.componentInstance.selectedModule.heatName).toEqual('base_vepdg'); + expect(fixture.componentInstance.selectedModule.name).toEqual('NewVf2..base_vepdg..module-0'); + }) + it('Try to update heat name and name but not find the module with the same uniqueId', () => { + selectedModuleMock.uniqueId = '2' + updateSelectedModuleMock(); + fixture.componentInstance.openEditModuleNamePopup(eventMock); + expect(fixture.componentInstance.selectedModule.updateName).toHaveBeenCalled(); + expect(modulesServiceMock.updateModuleMetadata).not.toHaveBeenCalled(); + expect(fixture.componentInstance.modules[0].name).toEqual('NewVf2..base_vepdg..module-0'); + expect(fixture.componentInstance.selectedModule.heatName).toEqual('base_vepdg'); + expect(fixture.componentInstance.selectedModule.name).toEqual('NewVf2..base_vepdg..module-0'); + selectedModuleMock.uniqueId = '1' + }) + it('Open edit module name popover and change the heat name', () => { + updateSelectedModuleMock(); + spyOn(fixture.componentInstance, 'updateHeatName'); + spyOn(fixture.componentInstance, 'updateOriginalHeatName'); + fixture.componentInstance.openEditModuleNamePopup(eventMock); + expect(popoverServiceMock.createPopOverWithInnerComponent).toHaveBeenCalled(); + expect(fixture.componentInstance.selectedModule.heatName).toEqual("new heat name"); + expect(fixture.componentInstance.updateHeatName).toHaveBeenCalled(); + }) + + + it('Open edit module name popover and not change the heat name', () => { + updateSelectedModuleMock(); + editModuleNameInstanceMock.innerPopoverContent.instance.clickButtonEvent = Observable.of(null); + fixture.componentInstance.openEditModuleNamePopup(eventMock); + expect(popoverServiceMock.createPopOverWithInnerComponent).toHaveBeenCalled(); + expect(fixture.componentInstance.selectedModule.heatName).toEqual("base_vepdg"); + }) +}); \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/hierarchy-tab/hierarchy-tab.component.ts b/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/hierarchy-tab/hierarchy-tab.component.ts new file mode 100644 index 0000000000..604b194283 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/hierarchy-tab/hierarchy-tab.component.ts @@ -0,0 +1,139 @@ +import {Component, Input} from "@angular/core"; +import {Component as TopologyTemplate, ComponentInstance, DisplayModule, Module, PropertyModel} from "app/models"; +import {TranslateService} from "app/ng2/shared/translator/translate.service"; +import {ComponentType} from "app/utils/constants"; +import {WorkspaceService} from "../../../../workspace.service"; +import {ModulesService} from "../../../../../../services/modules.service"; +import * as _ from "lodash"; +import {ModalsHandler} from "../../../../../../../utils/modals-handler"; +import {ComponentFactory} from "../../../../../../../utils/component-factory"; +import {Select, Store} from "@ngxs/store"; +import { SdcUiServices } from "onap-ui-angular"; +import { EditModuleName } from "../edit-module-name/edit-module-name.component"; +import {GraphState} from "../../../../../composition/common/store/graph.state"; +import {DeploymentGraphService} from "../../../../../composition/deployment/deployment-graph.service"; +import {OnSidebarOpenOrCloseAction} from "../../../../../composition/common/store/graph.actions"; + +@ Component({ + selector: 'hierarchy-tab', + templateUrl: './hierarchy-tab.component.html', + styleUrls: ['./hierarchy-tab.component.less'], +}) +export class HierarchyTabComponent { + + @Select(GraphState.withSidebar) withSidebar$: boolean; + @Input() isViewOnly: boolean; + public selectedIndex: number; + public selectedModule: DisplayModule; + public isLoading: boolean; + public topologyTemplateName: string; + public topologyTemplateType: string; + public modules: Array = []; + public componentInstances: Array = []; + private editPropertyModalTopologyTemplate: TopologyTemplate; + + constructor(private translateService: TranslateService, + private workspaceService: WorkspaceService, + private deploymentService: DeploymentGraphService, + private modulesService: ModulesService, + private ModalsHandler: ModalsHandler, + private componentFactory: ComponentFactory, + private store: Store, + private popoverService: SdcUiServices.PopoverService) { + this.isLoading = false; + this.topologyTemplateName = this.workspaceService.metadata.name; + this.topologyTemplateType = this.workspaceService.metadata.componentType; + } + + ngOnInit() { + this.modules = this.deploymentService.modules; + this.componentInstances = this.deploymentService.componentInstances; + this.editPropertyModalTopologyTemplate = this.componentFactory.createEmptyComponent(this.topologyTemplateType); + this.editPropertyModalTopologyTemplate.componentInstances = this.deploymentService.componentInstances; + } + + onModuleSelected(module: Module, componentInstanceId?: string): void { + + let onSuccess = (module: DisplayModule) => { + console.log("Module Loaded: ", module); + this.selectedModule = module; + this.isLoading = false; + }; + + let onFailed = () => { + this.isLoading = false; + }; + + if (!this.selectedModule || (this.selectedModule && this.selectedModule.uniqueId != module.uniqueId)) { + this.isLoading = true; + if (this.topologyTemplateType == ComponentType.SERVICE) { + // this.selectedInstanceId = componentInstanceId; + this.modulesService.getComponentInstanceModule(this.topologyTemplateType, this.workspaceService.metadata.uniqueId, componentInstanceId, module.uniqueId).subscribe((resultModule: DisplayModule) => { + onSuccess(resultModule); + }, () => { + onFailed(); + }); + } else { + this.modulesService.getModuleForDisplay(this.topologyTemplateType, this.workspaceService.metadata.uniqueId, module.uniqueId).subscribe((resultModule: DisplayModule) => { + onSuccess(resultModule); + }, () => { + onFailed(); + }); + } + } + } + + updateHeatName(): void { + this.isLoading = true; + let originalName: string = this.selectedModule.name; + + this.selectedModule.updateName(); + let moduleIndex: number = _.indexOf(this.modules, _.find(this.modules, (module: Module) => { + return module.uniqueId === this.selectedModule.uniqueId; + })); + + if (moduleIndex !== -1) { + this.modules[moduleIndex].name = this.selectedModule.name; + this.modulesService.updateModuleMetadata(this.topologyTemplateType, this.workspaceService.metadata.uniqueId, this.modules[moduleIndex]).subscribe(() => { + this.isLoading = false; + }, () => { + this.updateOriginalHeatName(originalName, moduleIndex); + this.modules[moduleIndex].name = originalName; + }); + } else { + this.updateOriginalHeatName(originalName, moduleIndex); + } + }; + + private updateOriginalHeatName(originalName: string, moduleIndex: number){ + this.isLoading = false; + this.selectedModule.name = originalName; + this.selectedModule.heatName = this.selectedModule.name.split('..')[1]; + } + + openEditPropertyModal(property: PropertyModel): void { + this.editPropertyModalTopologyTemplate.setComponentMetadata(this.workspaceService.metadata); + this.ModalsHandler.openEditModulePropertyModal(property, this.editPropertyModalTopologyTemplate, this.selectedModule, this.selectedModule.properties).then(() => { + }); + } + + private getKeys(map: Map) { + return _.keys(map); + } + + private toggleSidebarDisplay = () => { + // this.withSidebar = !this.withSidebar; + this.store.dispatch(new OnSidebarOpenOrCloseAction()); + } + + public openEditModuleNamePopup($event) { + const editModuleNameInstance = this.popoverService.createPopOverWithInnerComponent('Edit Module Name', '', {x:$event.x , y:$event.y }, EditModuleName, {selectModule: _.cloneDeep(this.selectedModule)}, 'top'); + editModuleNameInstance.innerPopoverContent.instance.clickButtonEvent.subscribe((newHeatName) => { + if(newHeatName != null){ + this.selectedModule.heatName = newHeatName; + this.updateHeatName(); + } + editModuleNameInstance.closePopover(); + }) + } +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/hierarchy-tab/hierarchy-tab.module.ts b/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/hierarchy-tab/hierarchy-tab.module.ts new file mode 100644 index 0000000000..048ca0c65f --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/deployment/panel/panel-tabs/hierarchy-tab/hierarchy-tab.module.ts @@ -0,0 +1,24 @@ +/** + * Created by ob0695 on 6/4/2018. + */ +import {NgModule} from "@angular/core"; +import {SdcUiComponentsModule} from "onap-ui-angular"; +import {HierarchyTabComponent} from "./hierarchy-tab.component"; +import {UiElementsModule} from "../../../../../../components/ui/ui-elements.module"; +import {TranslateModule} from "../../../../../../shared/translator/translate.module"; +import {CommonModule} from "@angular/common"; +import {GlobalPipesModule} from "../../../../../../pipes/global-pipes.module"; +import { EditModuleName } from "../edit-module-name/edit-module-name.component"; + +@NgModule({ + declarations: [HierarchyTabComponent, EditModuleName], + imports: [CommonModule, + UiElementsModule, + SdcUiComponentsModule, + TranslateModule, + GlobalPipesModule], + entryComponents: [HierarchyTabComponent, EditModuleName], + exports: [HierarchyTabComponent, EditModuleName], +}) +export class HierarchyTabModule { +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-artifact-table/distribution-component-artifact-table.component.html b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-artifact-table/distribution-component-artifact-table.component.html new file mode 100644 index 0000000000..574f2d1bb4 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-artifact-table/distribution-component-artifact-table.component.html @@ -0,0 +1,62 @@ +
+ + + +
+ {{ status.timeStamp | date:'short':'UTC'}} + {{ status.status }} +
+
+
+ + +
+ + + + + {{ componentName }} + +
+
+
+ + +
{{ row.name }}
+
+
+ + +
+ {{ row.url }} + + + + +
+
+
+ + +
{{ getLatestArtifact(row.name).timeStamp | date:'short':'UTC'}}
+
+
+ + +
{{ getLatestArtifact(row.name).status }}
+
+
+
+
\ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-artifact-table/distribution-component-artifact-table.component.less b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-artifact-table/distribution-component-artifact-table.component.less new file mode 100644 index 0000000000..81b8805792 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-artifact-table/distribution-component-artifact-table.component.less @@ -0,0 +1,78 @@ +:host ::ng-deep { + .ngx-datatable { + > div { + min-height: 5px; + } + } +} + +.datatable-header-cell { + text-align: left; + color: red; +} + +.statusHeaderTable { + color: #000000; + font-family: OpenSans-Bold, sans-serif; + font-size: 12px; + font-weight: bold; + float: left; +} + +.status { + padding-right: 30px; + color: #5a5a5a; + font-family: OpenSans-Regular, sans-serif; + font-size: 12px; +} + +.distributionIDBlock { + display: inline-block; +} + +.distributionRowContainer{ + background-color: #eaeaea; + text-align: center; +} + +.distributionRowLabel { + overflow: hidden; + padding-top: 10px; + color: #000000; + font-family: OpenSans-Semibold, sans-serif; + font-size: 12px; + font-weight: bold; +} + +.distributionRowValue { + color: #263d4d; + font-family: OpenSans-Regular, sans-serif; + font-size: 14px; +} + +.urlValue { + float: left; + color: #263d4d; + font-family: OpenSans-Regular, sans-serif; + font-size: 14px; +} + +.urlCopyIcon { + float: right; + width: 8%; +} + +.ellipsisCell { + width: 92%; + white-space: nowrap; + text-overflow: ellipsis; + overflow: hidden; +} + + + + + + + + diff --git a/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-artifact-table/distribution-component-artifact-table.component.spec.ts b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-artifact-table/distribution-component-artifact-table.component.spec.ts new file mode 100644 index 0000000000..72b930b6b8 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-artifact-table/distribution-component-artifact-table.component.spec.ts @@ -0,0 +1,90 @@ +import { NO_ERRORS_SCHEMA } from '@angular/core'; +import { ComponentFixture } from '@angular/core/testing'; +import { NgxDatatableModule } from '@swimlane/ngx-datatable'; +import { SdcUiServices } from 'onap-ui-angular'; +import { ConfigureFn, configureTests } from '../../../../../../../jest/test-config.helper'; +import { DistributionService } from '../../distribution.service'; +import { DistributionComponentArtifactTableComponent } from './distribution-component-artifact-table.component'; + +describe('DistributionComponentArtifactTableComponent', () => { + let fixture: ComponentFixture; + let distibutionServiceMock: Partial; + + const mockArtifactsForDistributionAndComponentName = [ + { + name: 'Artifact1', + statuses: [ + {timeStamp: '7/25/2019 12:48AM', status: 'DEPLOY_OK'}, + {timeStamp: '7/25/2019 12:48AM', status: 'DOWNLOAD_OK'}, + {timeStamp: '7/25/2019 12:48AM', status: 'NOTIFIED'} + ], + url: 'URL1', + }, + { + name: 'Artifact2', + statuses: [ + {timeStamp: '7/26/2019 12:48AM', status: 'STATUS_TO_DISPLAY'}, + {timeStamp: '7/25/2019 12:48AM', status: 'DOWNLOAD_OK'}, + {timeStamp: '7/25/2019 12:48AM', status: 'NOTIFIED'} + ], + url: 'URL2', + }, + { + name: 'ArtifactWithNoStatuses', + url: 'URL2', + } + ]; + + beforeEach(() => { + + distibutionServiceMock = { + getArtifactstByDistributionIDAndComponentsName: jest.fn().mockReturnValue(mockArtifactsForDistributionAndComponentName), + }; + + const configure: ConfigureFn = (testBed) => { + testBed.configureTestingModule({ + declarations: [DistributionComponentArtifactTableComponent], + imports: [NgxDatatableModule], + schemas: [NO_ERRORS_SCHEMA], + providers: [ + {provide: DistributionService, useValue: distibutionServiceMock} + ], + }); + }; + + configureTests(configure).then((testBed) => { + fixture = testBed.createComponent(DistributionComponentArtifactTableComponent); + }); + + }); + + it('Get Latest Artifact (status and timeStamp) - So the Component Table will display the last time stamp of the notification', async () => { + await fixture.componentInstance.ngOnInit(); + expect(fixture.componentInstance.getLatestArtifact('Artifact2')).toEqual({status: 'STATUS_TO_DISPLAY', timeStamp: '7/26/2019 12:48AM'}); + expect(fixture.componentInstance.getLatestArtifact('ArtifactWithNoStatuses')).toEqual(null); + }); + + it('Once the Distribution Component Artifact Table Component is created - artifacts will keep the relevant artifacts for a specific distributionID and Component Name', async () => { + await fixture.componentInstance.ngOnInit(); + // tslint:disable:no-string-literal + expect(fixture.componentInstance.artifacts.length).toBe(3); + expect(fixture.componentInstance.artifacts[0].name).toBe('Artifact1'); + expect(fixture.componentInstance.artifacts[0].url).toBe('URL1'); + expect(fixture.componentInstance.artifacts[0].statuses.length).toBe(3); + + expect(fixture.componentInstance.artifacts[1].name).toBe('Artifact2'); + }); + + it('Once the Distribution Component Artifact Table Component is created for Modal- artifacts will keep the relevant artifacts for a ' + + 'specific distributionID and Component Name filtered by Status', async () => { + fixture.componentInstance.statusFilter = 'DOWNLOAD_OK'; + await fixture.componentInstance.ngOnInit(); + expect(fixture.componentInstance.artifacts.length).toBe(3); + expect(fixture.componentInstance.artifacts[0].name).toBe('Artifact1'); + expect(fixture.componentInstance.artifacts[0].url).toBe('URL1'); + + expect(fixture.componentInstance.artifacts[0].statuses.length).toBe(1); + expect(fixture.componentInstance.artifacts[0].statuses[0]).toEqual({status: 'DOWNLOAD_OK', timeStamp: '7/25/2019 12:48AM'}); + + }); +}); diff --git a/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-artifact-table/distribution-component-artifact-table.component.ts b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-artifact-table/distribution-component-artifact-table.component.ts new file mode 100644 index 0000000000..af9aef5c64 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-artifact-table/distribution-component-artifact-table.component.ts @@ -0,0 +1,68 @@ +import { Component, Input, OnInit, ViewChild } from '@angular/core'; +import * as _ from 'lodash'; +import { DistributionService } from '../../distribution.service'; + +// tslint:disable:no-string-literal + +@Component({ + selector: 'app-distribution-component-artifact-table', + templateUrl: './distribution-component-artifact-table.component.html', + styleUrls: ['./distribution-component-artifact-table.component.less'] +}) +export class DistributionComponentArtifactTableComponent implements OnInit { + + @ViewChild('statusTable', {}) table: any; + + @Input() componentName: string; + @Input() rowDistributionID: string; + @Input() statusFilter: string; + + public artifacts = []; + + constructor(private distributionService: DistributionService) { + } + + ngOnInit() { + this.artifacts = this.distributionService.getArtifactstByDistributionIDAndComponentsName(this.rowDistributionID, this.componentName); + if (this.statusFilter) { + this.artifacts.forEach( + (artifact) => { + artifact.statuses = _.filter(artifact.statuses, {status: this.statusFilter}); + }); + } + } + + public getLatestArtifact(artifactName: string) { + const selectedArtifact = this.artifacts.filter((artifact) => artifact.name === artifactName); + if (selectedArtifact && selectedArtifact[0] && selectedArtifact[0]['statuses'] && selectedArtifact[0]['statuses'][0]) { + return selectedArtifact[0]['statuses'][0]; + } else { + return null; + } + } + + private copyToClipboard(urlToCopy: any) { + + const inputForCopyToClipboard = document.getElementById('inputForCopyToClipboard') as HTMLInputElement; + inputForCopyToClipboard.value = urlToCopy; + /* Select the text field */ + inputForCopyToClipboard.select(); + + /* Copy the text inside the text field */ + document.execCommand('copy'); + + } + + private generateDataTestID(preFix: string, componentName: string, artifactName: string, status?: string) { + if (!status) { + return preFix + componentName + '_' + artifactName; + } else { + return preFix + status + '_' + componentName + '_' + artifactName; + } + } + + private expandRow(row: any) { + this.table.rowDetail.toggleExpandRow(row); + } + +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-table.component.html b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-table.component.html new file mode 100644 index 0000000000..fa5a9ad7fb --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-table.component.html @@ -0,0 +1,47 @@ +
+
+ Total Artifacts {{ getTotalArtifactsForDistributionID(rowDistributionID) }} + Notified {{ getLengthArtifactsForDistributionIDByStatus(rowDistributionID, 'NOTIFIED') }} + Downloaded {{ getLengthArtifactsForDistributionIDByStatus(rowDistributionID, 'DOWNLOAD_OK') }} + Deployed {{ getLengthArtifactsForDistributionIDByStatus(rowDistributionID, 'DEPLOY_OK') }} + Not Notified {{ getLengthArtifactsForDistributionIDByStatus(rowDistributionID, 'NOT_NOTIFIED') }} + Deploy Errors {{ getLengthArtifactsForDistributionIDByStatus(rowDistributionID, 'DEPLOY_ERROR') }} + Download Errors {{ getLengthArtifactsForDistributionIDByStatus(rowDistributionID, 'DOWNLOAD_ERROR') }} +
+ + + + +
+
+ + + + {{ component }} {{ getTotalArtifactsForDistributionID(rowDistributionID, component) }} + Notified {{ getLengthArtifactsForDistributionIDByStatus(rowDistributionID, 'NOTIFIED', component) }} + Downloaded {{ getLengthArtifactsForDistributionIDByStatus(rowDistributionID, 'DOWNLOAD_OK', component) }} + Deployed {{ getLengthArtifactsForDistributionIDByStatus(rowDistributionID, 'DEPLOY_OK', component) }} + Not Notified {{ getLengthArtifactsForDistributionIDByStatus(rowDistributionID, 'NOT_NOTIFIED', component) }} + {{ getMSOStatus (rowDistributionID, component) }} + Deploy Errors {{ getLengthArtifactsForDistributionIDByStatus(rowDistributionID, 'DEPLOY_ERROR', component) }} + Download Errors {{ getLengthArtifactsForDistributionIDByStatus(rowDistributionID, 'DOWNLOAD_ERROR', component) }} +
+ + + +
+ +
+
+
+ diff --git a/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-table.component.less b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-table.component.less new file mode 100644 index 0000000000..3eab18ca14 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-table.component.less @@ -0,0 +1,66 @@ +.red { + color: red; +} + +.green { + color: green; +} + +.msoStatus { + padding-left: 5px; +} + +.blue { + color: #009fdb; + font-family: OpenSans-Semibold, sans-serif; + font-size: 14px; +} + +.rightVerticalSeperator { + border-right: 1px solid #d2d2d2; + padding-left: 5px; + padding-right: 5px; + cursor: pointer; +} + +.rightVerticalSeperatorComponent { + border-right: 1px solid #d2d2d2; + padding-left: 5px; + padding-right: 5px; +} + +.floatRight{ + float: right; +} + +.distributionSummary { + padding-top: 5px; + padding-bottom: 5px; + background-color: #eaeaea; + padding-left: 25px; + padding-right: 25px; +} + +.componentSummary { + margin-top: 5px; + margin-bottom: 5px; + padding-top: 5px; + padding-bottom: 5px; + background-color: #eaeaea; + padding-left: 25px; + padding-right: 25px; +} + +.componentShiftLeft { + margin-left: 15px; +} + +.titleSummaryFontSettings { + color: #191919; + font-family: OpenSans-Regular, sans-serif; + font-size: 14px; +} + + + + diff --git a/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-table.component.spec.ts b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-table.component.spec.ts new file mode 100644 index 0000000000..ff89b92fd8 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-table.component.spec.ts @@ -0,0 +1,47 @@ +import { NO_ERRORS_SCHEMA } from '@angular/core'; +import { ComponentFixture } from '@angular/core/testing'; +import { NgxDatatableModule } from '@swimlane/ngx-datatable'; +import { SdcUiServices } from 'onap-ui-angular'; +import { ConfigureFn, configureTests } from '../../../../../../jest/test-config.helper'; +import { DistributionService } from '../distribution.service'; +import { DistributionComponentTableComponent } from './distribution-component-table.component'; + +describe('DistributionComponentTableComponent', () => { + let fixture: ComponentFixture; + let distibutionServiceMock: Partial; + + const mockComponentsForDistribution = ['Consumer1', 'Consumer2']; + + beforeEach(() => { + + distibutionServiceMock = { + getComponentsByDistributionID: jest.fn().mockReturnValue(mockComponentsForDistribution), + getArtifactstByDistributionIDAndComponentsName: jest.fn(), + getArtifactsForDistributionIDAndComponentByStatus: jest.fn() + }; + + const configure: ConfigureFn = (testBed) => { + testBed.configureTestingModule({ + declarations: [DistributionComponentTableComponent], + imports: [NgxDatatableModule], + schemas: [NO_ERRORS_SCHEMA], + providers: [ + {provide: DistributionService, useValue: distibutionServiceMock}, + {provide: SdcUiServices.ModalService, useValue: {}} + ], + }); + }; + + configureTests(configure).then((testBed) => { + fixture = testBed.createComponent(DistributionComponentTableComponent); + }); + + }); + + it('Once the Distribution Component Table Component is created - components will keep the relevant components for a specific distributionID', async () => { + await fixture.componentInstance.ngOnInit(); + expect(fixture.componentInstance.components.length).toBe(2); + expect(fixture.componentInstance.components[0]).toBe('Consumer1'); + expect(fixture.componentInstance.components[1]).toBe('Consumer2'); + }); +}); diff --git a/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-table.component.ts b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-table.component.ts new file mode 100644 index 0000000000..e3aaf9d639 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution-component-table/distribution-component-table.component.ts @@ -0,0 +1,104 @@ +import { Component, Input, OnInit } from '@angular/core'; +import { SdcUiCommon, SdcUiComponents, SdcUiServices } from 'onap-ui-angular'; +import { ModalComponent } from 'onap-ui-angular/dist/modals/modal.component'; +import { DistributionComponent } from '../distribution.component'; +import { DistributionService } from '../distribution.service'; + +@Component({ + selector: 'app-distribution-component-table', + templateUrl: './distribution-component-table.component.html', + styleUrls: ['./distribution-component-table.component.less'] +}) +export class DistributionComponentTableComponent implements OnInit { + + @Input() rowDistributionID: string; + @Input() isModal: boolean = false; + @Input() statusFilter: string; + public components = []; + private customModalInstance: ModalComponent; + private expanded = []; + constructor(private distributionService: DistributionService, + private modalService: SdcUiServices.ModalService) { + } + + ngOnInit() { + this.initComponents(); + } + + private generateTotalComponentArtifactsLabel(componentName: any, status: string): string { + return 'total' + componentName + status + 'ArtifactsLabel'; + } + + private generateExpandDataTestID(componentName: string) { + return 'expandIcon_' + componentName; + } + + private initComponents() { + this.components = this.distributionService.getComponentsByDistributionID(this.rowDistributionID); + this.components.map((component) => this.expanded.push({componentName: component, expanded: false})); + } + + private getTotalArtifactsForDistributionID(distributionID: string, componentName?: string): number { + return this.distributionService.getArtifactstByDistributionIDAndComponentsName(distributionID, componentName).length; + } + + private getLengthArtifactsForDistributionIDByStatus(distributionID: string, statusToSerach: string, componentName?: string): number { + if (componentName) { + return this.distributionService.getArtifactsForDistributionIDAndComponentByStatus(distributionID, statusToSerach, componentName).length; + } else { + return this.distributionService.getArtifactsForDistributionIDAndComponentByStatus(distributionID, statusToSerach).length; + } + } + + private openModal(rowDistributionID: string, statusFilter: string) { + + const title: string = 'Distribution by Status'; + const attributeModalConfig = { + title, + size: 'sdc-xl', + type: SdcUiCommon.ModalType.custom, + buttons: [ + { + id: 'close', + text: 'Close', + size: 'sm', + closeModal: true, + disabled: false, + } + ] as SdcUiCommon.IModalButtonComponent[] + }; + + this.customModalInstance = this.modalService.openCustomModal(attributeModalConfig, DistributionComponent, { + // inputs + rowDistributionID, + statusFilter, + isModal: true, + }); + } + + private expandRow(componentName: string) { + console.log('Should expand componentSummary for componentName = ' + componentName); + const selectedComponent = this.expanded.find((component) => component.componentName === componentName); + // tslint:disable:no-string-literal + const selectedComponentExpandedVal = selectedComponent['expanded']; + // this.expanded = !this.expanded; + for (const i in this.expanded) { + if (this.expanded[i].componentName === componentName) { + this.expanded[i].expanded = !this.expanded[i].expanded; + break; //Stop this loop, we found it! + } + } + const selectedComponentAfter = this.expanded.find((component) => component.componentName === componentName); + const selectedComponentExpandedValAfter = selectedComponentAfter['expanded']; + } + + private isExpanded(componentName: string) { + const selectedComponent = this.expanded.find((component) => component.componentName === componentName); + return selectedComponent['expanded']; + } + + + private getMSOStatus(rowDistributionID: string, componentName: string): string { + return this.distributionService.getMSOStatus(rowDistributionID, componentName); + } +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.component.html b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.component.html new file mode 100644 index 0000000000..d0cacb054e --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.component.html @@ -0,0 +1,80 @@ +
+
+
DISTRIBUTION [{{distributions.length}}]
+
+ + +
+
+
No Distributions To Present
+
+ +
+ + + + + + + + +
+ + +
+
+
{{ row.distributionID }}
+
+
+
+ + +
{{ row.userId }}
+
+
+ + +
{{ row.timestamp }}
+
+
+ + +
+ + + + + {{ row.deployementStatus }} + + + + +
+
+
+
+
diff --git a/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.component.less b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.component.less new file mode 100644 index 0000000000..b630881fdc --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.component.less @@ -0,0 +1,92 @@ +:host ::ng-deep { + .ngx-datatable { + > div { + min-height: 500px; + datatable-body { + max-height: max-content; + } + } + } +} + +.w-sdc-distribution-view-header { + display: flex; + -webkit-justify-content: space-between; + margin: 0 25px 5px 40px; + + .header-spacer { + flex-grow: 5; + } + + .w-sdc-distribution-view-title{ + color: #191919; + font-family: OpenSans-Regular, sans-serif; + font-size: 14px; + line-height: 30px; + + + .blue-font { + color: #009fdb; + font-family: OpenSans-Semibold, sans-serif; + font-size: 14px; + } + } + +} + +.distribution-page { + max-height: 150px; +} + + .distributionIDBlock { + display: inline-block; + } + + .expand-collapse-cell { + display: inline-block; + } + + .statusIcon { + display: inline-block; + margin-right: 10px; + } + + .btnMarkAsDistributed { + float: right; + background-color: #E5F3FF; + border: 1px solid #8DCCD5; + width: 55px; + height: 21px; + text-align: center; + } + + .distributionRowContainer{ + background-color: #eaeaea; + text-align: center; + } + + .distributionRowLabel { + overflow: hidden; + padding-top: 10px; + color: #000000; + font-family: OpenSans-Semibold, sans-serif; + font-size: 12px; + font-weight: bold; + } + + .distributionRowValue { + color: #263d4d; + font-family: OpenSans-Regular, sans-serif; + font-size: 14px; + } + +.ellipsisCell { + width: 92%; + white-space: nowrap; + text-overflow: ellipsis; + overflow: hidden; +} + + + + diff --git a/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.component.spec.ts b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.component.spec.ts new file mode 100644 index 0000000000..e6c9c239e1 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.component.spec.ts @@ -0,0 +1,92 @@ +import { NO_ERRORS_SCHEMA } from '@angular/core'; +import { ComponentFixture } from '@angular/core/testing'; +import { NgxDatatableModule } from '@swimlane/ngx-datatable'; +import { SdcUiServices } from 'onap-ui-angular'; +import { ConfigureFn, configureTests } from '../../../../../jest/test-config.helper'; +import { ComponentMetadata } from '../../../../models/component-metadata'; +import { AuthenticationService } from '../../../services/authentication.service'; +import { WorkspaceService } from '../workspace.service'; +import { DistributionComponent } from './distribution.component'; +import { DistributionService } from './distribution.service'; +import {EventListenerService} from "../../../../services/event-listener-service"; + +describe('DistributionComponent', () => { + let fixture: ComponentFixture; + let distibutionServiceMock: Partial; + let workspaceServiceMock: Partial; + let loaderServiceMock: Partial; + let authenticationServiceMock: Partial ; + let eventListenerService: Partial ; + + const mockDistributionListFromService = [ + { + deployementStatus: 'Distributed', + distributionID: '1', + timestamp: '2019-07-21 08:37:02.834 UTC', + userId: 'Aretha Franklin(op0001)' + }, { + deployementStatus: 'Distributed', + distributionID: '2', + timestamp: '2019-07-21 09:37:02.834 UTC', + userId: 'Aretha Franklin(op0001)' + }]; + + beforeEach(() => { + + distibutionServiceMock = { + initDistributionsList: jest.fn(), + getDistributionList: jest.fn().mockReturnValue(mockDistributionListFromService), + initDistributionsStatusForDistributionID: jest.fn() + }; + + const componentMetadata = new ComponentMetadata(); + componentMetadata.uuid = '111'; + + workspaceServiceMock = { + metadata : componentMetadata + }; + + authenticationServiceMock = { + getLoggedinUser: jest.fn().mockReturnValue({role: 'designer'}) + }; + + eventListenerService = { + registerObserverCallback: jest.fn(), + unRegisterObserver: jest.fn() + } + + loaderServiceMock = { + activate: jest.fn(), + deactivate: jest.fn() + }; + + const configure: ConfigureFn = (testBed) => { + testBed.configureTestingModule({ + declarations: [DistributionComponent], + imports: [NgxDatatableModule], + schemas: [NO_ERRORS_SCHEMA], + providers: [ + {provide: DistributionService, useValue: distibutionServiceMock}, + {provide: WorkspaceService, useValue: workspaceServiceMock}, + {provide: SdcUiServices.LoaderService, useValue: loaderServiceMock}, + {provide: AuthenticationService, useValue: authenticationServiceMock}, + {provide: EventListenerService, useValue: eventListenerService} + ], + }); + }; + + configureTests(configure).then((testBed) => { + fixture = testBed.createComponent(DistributionComponent); + }); + + }); + + it('Once the Distribution Component is created - distributionsResponseFromServer save all the distributions from the Service', async () => { + fixture.componentInstance.componentUuid = 'componentUid'; + fixture.componentInstance.rowDistributionID = null; + fixture.componentInstance.isModal = false; + + await fixture.componentInstance.ngOnInit(); + expect(fixture.componentInstance.distributions.length).toBe(2); + }); +}); diff --git a/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.component.ts b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.component.ts new file mode 100644 index 0000000000..ca1b6292d3 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.component.ts @@ -0,0 +1,117 @@ +import { Component, Input, OnInit, ViewChild } from '@angular/core'; +import { SdcUiCommon, SdcUiServices } from 'onap-ui-angular'; +import { EventListenerService } from '../../../../services/event-listener-service'; +import { AuthenticationService } from '../../../services/authentication.service'; +import { WorkspaceService } from '../workspace.service'; +import { DistributionService } from './distribution.service'; +import { EVENTS } from '../../../../utils/constants'; + +@Component({ + selector: 'distribution', + templateUrl: './distribution.component.html', + styleUrls: ['../../../../../assets/styles/table-style.less', './distribution.component.less'] +}) +export class DistributionComponent implements OnInit { + + @ViewChild('distributionTable', { }) table: any; + + @Input() isModal: boolean = false; + @Input() statusFilter: string; + @Input() rowDistributionID: string; + public componentUuid: string; + public distributions = []; + private expanded: any = {}; + private serviceHasDistibutions: boolean = false; + private readonly uniqueId: string; + private userRole: string; + + constructor(private workspaceService: WorkspaceService, + private distributionService: DistributionService, + private loaderService: SdcUiServices.LoaderService, + private authService: AuthenticationService, + private eventListenerService: EventListenerService) { + this.componentUuid = this.workspaceService.metadata.uuid; + this.uniqueId = this.workspaceService.metadata.uniqueId; + } + + + + async ngOnInit() { + this.userRole = this.authService.getLoggedinUser().role; + this.eventListenerService.registerObserverCallback(EVENTS.ON_DISTRIBUTION_SUCCESS, async () => { + await this.refreshDistributions(); + }); + await this.initDistributions(this.componentUuid, this.rowDistributionID); + } + + ngOnDestroy(): void { + this.eventListenerService.unRegisterObserver(EVENTS.ON_DISTRIBUTION_SUCCESS); + } + + async initDistributions(componentUuid: string, specificDistributionID?: string) { + this.loaderService.activate(); + await this.distributionService.initDistributionsList(componentUuid); + this.distributions = this.distributionService.getDistributionList(); + this.distributions.length > 0 ? this.serviceHasDistibutions = true : this.serviceHasDistibutions = false; + if (specificDistributionID) { + this.distributions = this.distributionService.getDistributionList(specificDistributionID); + } + this.loaderService.deactivate(); + } + + getIconName(rowStatus: string ) { + if (rowStatus === 'Distributed') { + return 'distributed'; + } + if (rowStatus === 'Deployed') { + return 'v-circle'; + } + } + + getIconMode(rowStatus: string) { + if (rowStatus === 'Distributed') { + return 'primary'; + } + if (rowStatus === 'Deployed') { + return 'secondary'; + } + } + + private async markDeploy(distributionID: string, status: string) { + if (status === 'Distributed') { + console.log('Should send MarkDeploy POST Request ServiceID:' + this.uniqueId + ' DISTID:' + distributionID); + await this.distributionService.markDeploy(this.uniqueId, distributionID); + this.refreshDistributions(); + } + } + + private async refreshDistributions() { + await this.initDistributions(this.componentUuid); + } + + private updateFilter(event) { + const val = event.target.value.toLowerCase(); + + // filter our data + this.distributions = this.distributionService.getDistributionList().filter((distribution: any[]) => { + return !val || + // tslint:disable:no-string-literal + distribution['distributionID'].toLowerCase().indexOf(val) !== -1; + }); + } + + private generateDataTestID(preFix: string, distributionID: string, isModal?: boolean ): string { + if (isModal) { + return preFix + distributionID.substring(0, 5) + '_Modal'; + } else { + return preFix + distributionID.substring(0, 5); + } + } + + private async expandRow(row: any, expanded: boolean) { + if (!expanded) { + await this.distributionService.initDistributionsStatusForDistributionID(row.distributionID); + } + this.table.rowDetail.toggleExpandRow(row); + } +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.module.ts b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.module.ts new file mode 100644 index 0000000000..723a6d8c0a --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.module.ts @@ -0,0 +1,34 @@ +import { CommonModule } from '@angular/common'; +import { NgModule } from '@angular/core'; +import { NgxDatatableModule } from '@swimlane/ngx-datatable'; +import { SdcUiComponentsModule } from 'onap-ui-angular'; +import { DistributionComponentArtifactTableComponent } from './distribution-component-table/distribution-component-artifact-table/distribution-component-artifact-table.component'; +import { DistributionComponentTableComponent } from './distribution-component-table/distribution-component-table.component'; +import { DistributionComponent } from './distribution.component'; +import { DistributionService } from './distribution.service'; + +@NgModule({ + declarations: [ + DistributionComponent, + DistributionComponentTableComponent, + DistributionComponentArtifactTableComponent, + ], + imports: [ + // TranslateModule, + CommonModule, + SdcUiComponentsModule, + NgxDatatableModule, + ], + exports: [ + DistributionComponent, + DistributionComponentTableComponent + ], + entryComponents: [ + DistributionComponent, + DistributionComponentTableComponent, + DistributionComponentArtifactTableComponent + ], + providers: [DistributionService] +}) +export class DistributionModule { +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.service.ts b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.service.ts new file mode 100644 index 0000000000..ed6791c5c1 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/disribution/distribution.service.ts @@ -0,0 +1,233 @@ +import { HttpClient } from '@angular/common/http'; +import { Inject, Injectable } from '@angular/core'; +import { tap } from 'rxjs/operators'; +import { Distribution } from '../../../../models/distribution'; +import { ISdcConfig, SdcConfigToken } from '../../../config/sdc-config.config'; + +@Injectable() +export class DistributionService { + protected baseUrl; + private distributionList = []; + private distributionStatusesMap = {}; + + // tslint:disable:no-string-literal + + constructor(protected http: HttpClient, @Inject(SdcConfigToken) sdcConfig: ISdcConfig) { + this.baseUrl = sdcConfig.api.root + sdcConfig.api.component_api_root; + } + + // Once the distribution page is loaded or when the user wants to refresh the list + async initDistributionsList(componentUuid: string): Promise { + const distributionsListURL = this.baseUrl + 'services/' + componentUuid + '/distribution'; + const res = this.http.get(distributionsListURL).pipe(tap( (result) => { + this.distributionList = result['distributionStatusOfServiceList']; + this.insertDistrbutionsToMap(); + } )); + return res.toPromise(); + } + + // Once the user click on the relevant distribution ID in the distribution table (open and close) + async initDistributionsStatusForDistributionID(distributionID: string): Promise { + const distributionStatus = this.baseUrl + 'services/distribution/' + distributionID; + const res = this.http.get(distributionStatus).pipe(tap( (result) => { + this.insertDistributionStatusToDistributionsMap(distributionID, result['distributionStatusList']); + } )); + return res.toPromise(); + } + + public getDistributionList(specificDistributionID?: string) { + if (specificDistributionID) { + return this.distributionList.filter((distribution) => { + return distribution['distributionID'] === specificDistributionID; + }); + } else { + return this.distributionList; + } + } + + public getComponentsByDistributionID(distributionID: string) { + const components = []; + const distributionStatusMap = this.getStatusMapForDistributionID(distributionID); + if (distributionStatusMap) { + distributionStatusMap.forEach((component) => components.push(component.componentID)); + } + return components; + } + + // get array of artifacts per distributionID w/o componentName, sliced by artifact status + public getArtifactsForDistributionIDAndComponentByStatus(distributionID: string, statusToSearch: string, componentName?: string) { + const filteredArtifactsByStatus = []; + + if (componentName) { + this.getArtifactstByDistributionIDAndComponentsName(distributionID, componentName).forEach ( (artifact) => { + if (this.artifactStatusHasMatch(artifact, statusToSearch)) { + filteredArtifactsByStatus.push(artifact); + } + } ); + } else { + this.getArtifactstByDistributionIDAndComponentsName(distributionID).forEach ( (artifact) => { + if (this.artifactStatusHasMatch(artifact, statusToSearch)) { + filteredArtifactsByStatus.push(artifact); + } + } ); + } + return filteredArtifactsByStatus; + } + + public getArtifactstByDistributionIDAndComponentsName(distributionID: string, componentName?: string): any[] { + const artifacts = []; + if (this.getStatusMapForDistributionID(distributionID)) { + if (componentName) { + if (this.getStatusMapForDistributionID(distributionID).filter((component) => component.componentID === componentName).length > 0) { + const artifactsArr = this.getStatusMapForDistributionID(distributionID).filter((component) => component.componentID === componentName)[0]['artifacts'] + if (artifactsArr.length > 0) { + artifactsArr.forEach((artifact) => { + const artifactObj = { + url: artifact.artifactUrl, + name: artifact.artifactName, + statuses: artifact.statuses + }; + artifacts.push(artifactObj); + }); + } + } + } else { + const components = this.getComponentsByDistributionID(distributionID); + components.forEach((componentName) => { + if (this.getStatusMapForDistributionID(distributionID).filter((component) => component.componentID === componentName).length > 0) { + const artifactsArr = this.getStatusMapForDistributionID(distributionID).filter((component) => component.componentID === componentName)[0]['artifacts'] + if (artifactsArr.length > 0) { + artifactsArr.forEach((artifact) => { + const artifactObj = { + url: artifact.artifactUrl, + name: artifact.artifactName, + statuses: artifact.statuses + }; + artifacts.push(artifactObj); + }); + } + } + }); + } + } + return artifacts; + } + + public getStatusMapForDistributionID(distributionID: string) { + return this.distributionStatusesMap[distributionID]; + } + + public markDeploy(uniqueId: string, distributionID: string): Promise { + const distributionStatus = this.baseUrl + 'services/' + uniqueId + '/distribution/' + distributionID + '/markDeployed'; + const res = this.http.post(distributionStatus, {}).pipe(tap( (result) => { + console.log(result); + } )); + return res.toPromise(); + } + + public getMSOStatus(distributionID: string, componentName: string): string { + const msoStatus = this.distributionStatusesMap[distributionID].filter((component) => component.componentID === componentName)[0].msoStatus; + return msoStatus ? msoStatus : ''; + } + + private artifactStatusHasMatch(artifact: any, statusToSerach: string) { + for (let i = 0; i < artifact.statuses.length; i++) { + if (artifact.statuses[i].status === statusToSerach) { + return true; + } + } + return false; + } + + private insertDistributionStatusToDistributionsMap(distributionID: string, distributionStatusMapResponseFromServer: object[]) { + + // // Clear the Distribution ID array - to avoid statuses duplications + const distribution = this.distributionStatusesMap[distributionID]; + distribution.length = 0; + + // Sort the response of statuses from Server, so it will be easy to pop the latest status when it will be required + const sortedResponseByTimeStamp = distributionStatusMapResponseFromServer.sort((a, b) => b['timestamp'] - a['timestamp']) + + sortedResponseByTimeStamp.map((distributionStatus) => { + const formattedDate = this.formatDate(distributionStatus['timestamp']); + + // if (distributionStatus['url'] === null) { + // distributionStatus['url'] = ""; + // } + + const detailedArtifactStatus = { + componentID: distributionStatus['omfComponentID'], + artifactName: distributionStatus['url']? distributionStatus['url'].split('/').pop() : '', + url: distributionStatus['url'], + time: distributionStatus['timestamp'], + status: distributionStatus['status'], + }; + + + + // Add Component to this.distributionStatusesMap in case not exist. + let componentPosition = _.findIndex(distribution, {componentID: detailedArtifactStatus.componentID}) + + if (componentPosition === -1) { + this.addComponentIdToDistributionStatusMap(distributionID, detailedArtifactStatus.componentID); + componentPosition = distribution.length - 1; + } + + const component = distribution[componentPosition]; + + + // Add Artifact to this.distributionStatusesMap[componentID] in case not exist. + let artifactPosition = _.findIndex(component.artifacts, {artifactUrl: detailedArtifactStatus.url}) + + if (artifactPosition === -1) { + this.addArtifactToComponentId(distributionID, componentPosition, detailedArtifactStatus.artifactName, detailedArtifactStatus.url); + artifactPosition = component.artifacts.length - 1; + } + + + // Add status to relevat artifact in relevent componentID. + if (detailedArtifactStatus.url) { + // Case where there is a url -> should add its status + component.artifacts[artifactPosition].statuses.push({ + timeStamp: detailedArtifactStatus.time, + status: detailedArtifactStatus.status + }); + } else { + // Should update the Component -> status from MSO + this.distributionStatusesMap[distributionID][componentPosition].msoStatus = detailedArtifactStatus.status; + } + + + }); + } + + private addComponentIdToDistributionStatusMap(distributionID: string, componentIDValue: string) { + this.distributionStatusesMap[distributionID].push({ + componentID: componentIDValue, + msoStatus: null, + artifacts: [] + }); + } + + private addArtifactToComponentId(distributionID: string, componentPosition: number, artifactNameValue: string, artifactURLValue: any) { + if (artifactNameValue) { + this.distributionStatusesMap[distributionID][componentPosition].artifacts.push({ + artifactName: artifactNameValue, + artifactUrl: artifactURLValue, + statuses: [] + }); + } + } + + private insertDistrbutionsToMap() { + this.distributionList.map((distribution) => this.distributionStatusesMap[distribution.distributionID] = []); + } + + private formatDate(epochTime: string) { + const intEpochTime = new Date(parseInt(epochTime, 10)); + const amOrPm = (intEpochTime.getHours() + 24) % 24 > 12 ? 'PM' : 'AM'; + const formattedDate = (intEpochTime.getMonth() + 1) + '/' + intEpochTime.getDate() + '/' + intEpochTime.getFullYear() + ' ' + intEpochTime.getHours() + ':' + + intEpochTime.getMinutes() + amOrPm; + return formattedDate; + } +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/information-artifact/__snapshots__/informational-artifact-page.spec.ts.snap b/catalog-ui/src/app/ng2/pages/workspace/information-artifact/__snapshots__/informational-artifact-page.spec.ts.snap new file mode 100644 index 0000000000..1a19b36cfb --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/information-artifact/__snapshots__/informational-artifact-page.spec.ts.snap @@ -0,0 +1,40 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`informational artifacts page should match current snapshot of informational artifact pages component 1`] = ` + +
+ + +
+ + + + + + + + + +
+
+
+
+`; diff --git a/catalog-ui/src/app/ng2/pages/workspace/information-artifact/information-artifact-page.component.html b/catalog-ui/src/app/ng2/pages/workspace/information-artifact/information-artifact-page.component.html new file mode 100644 index 0000000000..cff33258ae --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/information-artifact/information-artifact-page.component.html @@ -0,0 +1,82 @@ +
+ + + + +
{{row.description}}
+
+
+ + +
+ + {{row.artifactDisplayName }} +
+
+
+ + + {{row.artifactType}} + + + + + {{ row.artifactVersion }} + + + + + {{ row.artifactUUID }} + + + + +
+ + + +
+
+
+ + + +
+ + +
+
+
+
+
\ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/information-artifact/information-artifact-page.component.less b/catalog-ui/src/app/ng2/pages/workspace/information-artifact/information-artifact-page.component.less new file mode 100644 index 0000000000..b69e511f70 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/information-artifact/information-artifact-page.component.less @@ -0,0 +1,29 @@ +.information-artifact-page { + + .add-artifact-btn { + display: flex; + cursor: pointer; + justify-content: flex-end; + margin-bottom: 10px; + } + .download-artifact-button { + display: flex; + justify-content: center; + + .action-icon{ + margin-right: 10px; + } + } + + .add-artifacts-dynamic-btn-list { + display: flex; + flex-direction: column; + align-items: center; + width: 100%; + margin: 20px 0px; + .add-artifacts-dynamic-btn{ + width: 350px; + margin-top: 15px; + } + } +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/information-artifact/information-artifact-page.component.ts b/catalog-ui/src/app/ng2/pages/workspace/information-artifact/information-artifact-page.component.ts new file mode 100644 index 0000000000..a6804a43c6 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/information-artifact/information-artifact-page.component.ts @@ -0,0 +1,69 @@ +import {Component, OnInit, ViewChild} from "@angular/core"; +import {WorkspaceService} from "../workspace.service"; +import {SdcUiCommon, SdcUiComponents, SdcUiServices} from "onap-ui-angular"; +import {TopologyTemplateService} from "../../../services/component-services/topology-template.service"; +import * as _ from "lodash"; +import {ArtifactGroupType, ArtifactType} from "../../../../utils/constants"; +import {ArtifactsService} from "../../../components/forms/artifacts-form/artifacts.service"; +import {DeleteArtifactAction, GetArtifactsByTypeAction} from "../../../store/actions/artifacts.action"; +import {Select, Store} from "@ngxs/store"; +import {Observable} from "rxjs/index"; +import {ArtifactsState} from "../../../store/states/artifacts.state"; +import {map} from "rxjs/operators"; +import {WorkspaceState} from "../../../store/states/workspace.state"; +import {ArtifactModel} from "../../../../models/artifacts"; + +@Component({ + selector: 'information-artifact-page', + templateUrl: './information-artifact-page.component.html', + styleUrls: ['./information-artifact-page.component.less', '../../../../../assets/styles/table-style.less'] +}) +export class InformationArtifactPageComponent implements OnInit { + + public componentId: string; + public componentType: string; + public informationArtifacts$: Observable; + public informationArtifactsAsButtons$: Observable; + @Select(WorkspaceState.isViewOnly) isViewOnly$: boolean; + @ViewChild('informationArtifactsTable') table: any; + + constructor(private workspaceService: WorkspaceService, + private artifactsService: ArtifactsService, + private store: Store) { + } + + ngOnInit(): void { + this.componentId = this.workspaceService.metadata.uniqueId; + this.componentType = this.workspaceService.metadata.componentType; + + this.store.dispatch(new GetArtifactsByTypeAction({ + componentType: this.componentType, + componentId: this.componentId, + artifactType: ArtifactGroupType.INFORMATION + })); + + let artifacts = this.store.select(ArtifactsState.getArtifactsByType).pipe(map(filterFn => filterFn(ArtifactType.INFORMATION))); + this.informationArtifacts$ = artifacts.pipe(map(artifacts => _.filter(artifacts, (artifact) => { + return artifact.esId; + }))); + + this.informationArtifactsAsButtons$ = artifacts.pipe(map(artifacts => _.filter(artifacts, (artifact) => { + return !artifact.esId; + }))); + } + + onActivate(event) { + if (event.type === 'click') { + this.table.rowDetail.toggleExpandRow(event.row); + } + } + + public addOrUpdateArtifact = (artifact: ArtifactModel, isViewOnly?: boolean) => { + this.artifactsService.openArtifactModal(this.componentId, this.componentType, artifact, ArtifactGroupType.INFORMATION, isViewOnly); + } + + public deleteArtifact = (artifactToDelete) => { + this.artifactsService.deleteArtifact(this.componentType, this.componentId, artifactToDelete) + } + +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/information-artifact/information-artifact-page.module.ts b/catalog-ui/src/app/ng2/pages/workspace/information-artifact/information-artifact-page.module.ts new file mode 100644 index 0000000000..5eb9e5851b --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/information-artifact/information-artifact-page.module.ts @@ -0,0 +1,30 @@ +import {CommonModule} from "@angular/common"; +import {NgModule} from "@angular/core"; +import {SdcUiComponentsModule} from "onap-ui-angular"; +import {NgxDatatableModule} from "@swimlane/ngx-datatable"; +import {UiElementsModule} from "../../../components/ui/ui-elements.module"; +import {InformationArtifactPageComponent} from "./information-artifact-page.component"; +import {ArtifactFormModule} from "../../../components/forms/artifacts-form/artifact-form.module"; +import {ArtifactsService} from "../../../components/forms/artifacts-form/artifacts.service"; + +@NgModule({ + declarations: [ + InformationArtifactPageComponent + ], + imports: [ + CommonModule, + SdcUiComponentsModule, + NgxDatatableModule, + UiElementsModule, + ArtifactFormModule + ], + exports: [ + InformationArtifactPageComponent + ], + entryComponents: [ + InformationArtifactPageComponent + ], + providers:[ArtifactsService] +}) +export class InformationArtifactPageModule { +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/information-artifact/informational-artifact-page.spec.ts b/catalog-ui/src/app/ng2/pages/workspace/information-artifact/informational-artifact-page.spec.ts new file mode 100644 index 0000000000..10fd14739b --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/information-artifact/informational-artifact-page.spec.ts @@ -0,0 +1,77 @@ +import {async, ComponentFixture, TestBed} from "@angular/core/testing"; +import {NO_ERRORS_SCHEMA} from "@angular/core"; +import {ConfigureFn, configureTests} from "../../../../../jest/test-config.helper"; +import {NgxDatatableModule} from "@swimlane/ngx-datatable"; +import {WorkspaceService} from "../workspace.service"; +import {SdcUiServices} from "onap-ui-angular"; +import {TopologyTemplateService} from "../../../services/component-services/topology-template.service"; +import {Observable} from "rxjs/Observable"; +import {ComponentMetadata} from "../../../../models/component-metadata"; +import 'rxjs/add/observable/of'; +import {NgxsModule, Store} from "@ngxs/store"; +import {ArtifactsState} from "../../../store/states/artifacts.state"; +import {InformationArtifactPageComponent} from "./information-artifact-page.component"; +import { informationalArtifactsMock} from "../../../../../jest/mocks/artifacts-mock"; +import {ArtifactsService} from "../../../components/forms/artifacts-form/artifacts.service"; + +describe('informational artifacts page', () => { + + let fixture: ComponentFixture; + let topologyTemplateServiceMock: Partial; + let workspaceServiceMock: Partial; + let loaderServiceMock: Partial; + let store: Store; + + beforeEach( + async(() => { + + topologyTemplateServiceMock = { + getArtifactsByType: jest.fn().mockImplementation((componentType, id, artifactType) => Observable.of(informationalArtifactsMock)) + }; + workspaceServiceMock = {metadata: {uniqueId: 'service_unique_id', componentType: 'SERVICE'}} + + loaderServiceMock = { + activate : jest.fn(), + deactivate: jest.fn() + } + const configure: ConfigureFn = testBed => { + testBed.configureTestingModule({ + declarations: [InformationArtifactPageComponent], + imports: [NgxDatatableModule, NgxsModule.forRoot([ArtifactsState])], + schemas: [NO_ERRORS_SCHEMA], + providers: [ + {provide: WorkspaceService, useValue: workspaceServiceMock}, + {provide: TopologyTemplateService, useValue: topologyTemplateServiceMock}, + {provide: SdcUiServices.LoaderService, useValue: loaderServiceMock }, + {provide: ArtifactsService, useValue: {}}, + ], + }); + }; + + configureTests(configure).then(testBed => { + fixture = testBed.createComponent(InformationArtifactPageComponent); + store = testBed.get(Store); + }); + }) + ); + + it('should match current snapshot of informational artifact pages component', () => { + expect(fixture).toMatchSnapshot(); + }); + + it('should see exactly 3 informational artifacts and six buttons to add artifact by template', () => { + fixture.componentInstance.ngOnInit(); + fixture.componentInstance.informationArtifacts$.subscribe((artifacts)=> { + expect(artifacts.length).toEqual(3); + }) + fixture.componentInstance.informationArtifactsAsButtons$.subscribe((artifacts)=> { + expect(artifacts.length).toEqual(6); + }) + + store.selectOnce(state => state.artifacts.artifacts).subscribe(artifacts => { + expect(artifacts.length).toEqual(9); + }); + }) + + +}); \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities-properties/capabilities-properties.html b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities-properties/capabilities-properties.html new file mode 100644 index 0000000000..f496e64c17 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities-properties/capabilities-properties.html @@ -0,0 +1,22 @@ +
+ + + + {{row[column.prop]}} + + + {{row[column.prop].property.type}} + + + {{row[column.prop]}} + + + +
\ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities-properties/capabilities-properties.less b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities-properties/capabilities-properties.less new file mode 100644 index 0000000000..007f509538 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities-properties/capabilities-properties.less @@ -0,0 +1,9 @@ + +:host ::ng-deep { + .ngx-datatable { + > div { + min-height: auto !important; + } + + } +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities-properties/capabilities-properties.ts b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities-properties/capabilities-properties.ts new file mode 100644 index 0000000000..2a1a16e265 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities-properties/capabilities-properties.ts @@ -0,0 +1,33 @@ + +import { ViewChild, Input, OnInit, Component } from "@angular/core"; +import {SdcUiServices} from "onap-ui-angular"; +import { ModalsHandler } from "../../../../../../utils/modals-handler"; +import { WorkspaceService } from "../../../workspace.service"; +import { PropertyModel } from "../../../../../../models/properties"; + + +@Component({ + selector: 'capabilities-properties', + templateUrl: './capabilities-properties.html', + styleUrls: ['./capabilities-properties.less', '../../../../../../../assets/styles/table-style.less'] +}) +export class CapabilitiesPropertiesComponent { + @Input() public capabilitiesProperties: Array = []; + + private capabilityPropertiesColumns = [ + {name: 'Name', prop: 'name', flexGrow: 1}, + {name: 'Type', prop: 'type', flexGrow: 1}, + {name: 'Schema', prop: 'schema', flexGrow: 1}, + {name: 'Description', prop: 'description', flexGrow: 1}, + ]; + constructor(private modalsHandler: ModalsHandler, + private workspaceService: WorkspaceService) {} + + private updateProperty(property: PropertyModel): void { + _.forEach(this.capabilitiesProperties, (prop: PropertyModel) => { + prop.readonly = true; + }); + this.modalsHandler.openEditPropertyModal(property, this.workspaceService.metadata, this.capabilitiesProperties, false, 'component', + this.workspaceService.metadata.uniqueId); + } +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities.component.html b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities.component.html new file mode 100644 index 0000000000..819eb84849 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities.component.html @@ -0,0 +1,59 @@ +
+
+ + + + +
+ + + +
Properties
+ +
+
+ + +
+ + {{row.name}} +
+
+
+ + + {{row.type ? row.type.replace("tosca.capabilities.",""): ''}} + + + + + {{row.description}} + + + + + + {{row.validSourceTypes ? row.validSourceTypes.join(','): ''}} + + + + + + {{row.minOccurrences}},{{row.maxOccurrences}} + + +
+
\ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities.component.less b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities.component.less new file mode 100644 index 0000000000..0c520a8135 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities.component.less @@ -0,0 +1,16 @@ +:host ::ng-deep { + .datatable-row-detail { + width: 1260px; + } + .datatable-body-row { + cursor: pointer; + } +} +.expand-collapse-all-rows { + position: absolute; + top: 172px; + left: 890px; +} +.properties-title { + padding-bottom: 10px; +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities.component.ts b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities.component.ts new file mode 100644 index 0000000000..02db5d3aee --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilities.component.ts @@ -0,0 +1,79 @@ +import {Capability, CapabilityUI} from "../../../../../models/capability"; +import { ViewChild, Input, OnInit, Component } from "@angular/core"; +import {SdcUiServices} from "onap-ui-angular"; +import {CapabilitiesEditorComponent} from "./capabilityEditor/capabilities-editor.component"; +import {WorkspaceService} from "../../workspace.service"; +import {TopologyTemplateService} from "../../../../services/component-services/topology-template.service"; +import {ReqAndCapabilitiesService} from "../req-and-capabilities.service"; +import {ModalComponent} from "onap-ui-angular/dist/modals/modal.component"; +import {EventListenerService} from "../../../../../services/event-listener-service"; + + +@Component({ + selector: 'capabilities', + templateUrl: './capabilities.component.html', + styleUrls: ['./capabilities.component.less','../../../../../../assets/styles/table-style.less'] +}) +export class CapabilitiesComponent { + @Input() public capabilities: Array; + @ViewChild('capabilitiesTable') capabilitiesTable: any; + private customModalInstance: ModalComponent; + + constructor( + private workspaceService: WorkspaceService, + private loaderService: SdcUiServices.LoaderService, + private topologyTemplateService: TopologyTemplateService, + private reqAndCapabilitiesService : ReqAndCapabilitiesService, + private modalService: SdcUiServices.ModalService, + private eventListenerService: EventListenerService) { + } + + private onSelectCapabilities({ selected }) { + } + + editCapability(cap: CapabilityUI) { + let modalConfig = { + size: 'md', + title: 'Update Capability', + type: 'custom', + buttons: [ + { + id: 'saveButton', + text: ('Update'), + size: "'x-small'", + callback: () => this.updateCapability(), + closeModal: true + }, + {text: "Cancel", size: "'x-small'", closeModal: true}] + }; + let modalInputs = { + capability: cap, + capabilityTypesList: this.reqAndCapabilitiesService.getCapabilityTypesList(), + }; + + this.customModalInstance = this.modalService.openCustomModal(modalConfig, CapabilitiesEditorComponent, {input: modalInputs}); + this.customModalInstance.innerModalContent.instance. + onValidationChange.subscribe((isValid) => this.customModalInstance.getButtonById('saveButton').disabled = !isValid); + } + + expendRow(row) { + this.capabilitiesTable.rowDetail.toggleExpandRow(row); + } + + private updateCapability() { + const capability = this.customModalInstance.innerModalContent.instance.capabilityData; + this.loaderService.activate(); + if (capability.uniqueId) { + this.topologyTemplateService.updateCapability(this.workspaceService.metadata.getTypeUrl(), this.workspaceService.metadata.uniqueId, capability).subscribe((result) => { + let index = this.capabilities.findIndex((cap) => result[0].uniqueId === cap.uniqueId); + this.capabilities[index] = new CapabilityUI(result[0], this.workspaceService.metadata.uniqueId); + this.loaderService.deactivate(); + this.eventListenerService.notifyObservers('CAPABILITIES_UPDATED'); + }, () => { + this.loaderService.deactivate(); + }); + } + } + + +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilityEditor/capabilities-editor.component.html b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilityEditor/capabilities-editor.component.html new file mode 100644 index 0000000000..bc15d4d228 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilityEditor/capabilities-editor.component.html @@ -0,0 +1,93 @@ +
+
+
+
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+ + + + + +
+
+
+
+
+
\ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilityEditor/capabilities-editor.component.less b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilityEditor/capabilities-editor.component.less new file mode 100644 index 0000000000..324dc6c4d2 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilityEditor/capabilities-editor.component.less @@ -0,0 +1,38 @@ +@import '../../../../../../../assets/styles/variables.less'; + +.capability-editor { + .i-sdc-form-content-capability-content { + padding: 10px 25px; + .group-with-border { + margin: 25px 0; + padding: 15px 0; + border-top: 1px solid @tlv_color_u; + border-bottom: 1px solid @tlv_color_u; + .content-row:not(:last-of-type) { + padding-bottom: 13px; + } + } + + .occurrences-label { + font-family: @font-opensans-bold; + margin-bottom: 19px; + } + .occurrences-section, /deep/ .max-occurrences-value { + display: flex; + .min-occurrences-value { + padding-right: 30px; + } + .unbounded-value { + padding-top: 7px; + padding-right: 20px; + .sdc-checkbox__label { + text-transform: capitalize; + } + } + } + textarea { + min-height: unset; + height: unset; + } + } +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilityEditor/capabilities-editor.component.ts b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilityEditor/capabilities-editor.component.ts new file mode 100644 index 0000000000..3bafa42e0f --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilityEditor/capabilities-editor.component.ts @@ -0,0 +1,81 @@ +import {Component} from '@angular/core'; +import {ServiceServiceNg2} from "app/ng2/services/component-services/service.service"; +import {Capability, CapabilityTypeModel} from 'app/models'; +import {DropdownValue} from "app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component"; +import {TranslateService} from 'app/ng2/shared/translator/translate.service'; +import {Subject} from "rxjs"; + +@Component({ + selector: 'capabilities-editor', + templateUrl: './capabilities-editor.component.html', + styleUrls: ['./capabilities-editor.component.less'], + providers: [ServiceServiceNg2] +}) + +export class CapabilitiesEditorComponent { + input: { + test: string, + capability: Capability, + capabilityTypesList: Array, + isReadonly: boolean; + }; + capabilityData: Capability; + capabilityTypesMappedList: Array; + isUnboundedChecked: boolean; + isReadonly: boolean; + translatedUnboundTxt: string; + + public onValidationChange: Subject = new Subject(); + + constructor(private translateService: TranslateService) { + } + + ngOnInit() { + this.capabilityData = new Capability(this.input.capability); + this.translatedUnboundTxt = ''; + this.capabilityData.minOccurrences = this.capabilityData.minOccurrences || 0; + this.translateService.languageChangedObservable.subscribe(lang => { + this.translatedUnboundTxt = this.translateService.translate('REQ_CAP_OCCURRENCES_UNBOUNDED'); + this.capabilityData.maxOccurrences = this.capabilityData.maxOccurrences || this.translatedUnboundTxt; + this.isUnboundedChecked = this.capabilityData.maxOccurrences === this.translatedUnboundTxt; + }); + this.capabilityTypesMappedList = _.map(this.input.capabilityTypesList, capType => new DropdownValue(capType.toscaPresentation.type, capType.toscaPresentation.type)); + this.isReadonly = this.input.isReadonly; + this.validityChanged(); + } + + onUnboundedChanged() { + this.isUnboundedChecked = !this.isUnboundedChecked; + this.capabilityData.maxOccurrences = this.isUnboundedChecked ? this.translatedUnboundTxt : null; + this.validityChanged(); + } + + checkFormValidForSubmit() { + return this.capabilityData.name && this.capabilityData.name.length && + this.capabilityData.type && this.capabilityData.type.length && !_.isEqual(this.capabilityData.minOccurrences, "") && this.capabilityData.minOccurrences >= 0 && + ( + this.isUnboundedChecked || + (this.capabilityData.maxOccurrences && (this.capabilityData.minOccurrences <= parseInt(this.capabilityData.maxOccurrences))) + ); + } + + onSelectCapabilityType(selectedCapType: DropdownValue) { + this.capabilityData.type = selectedCapType && selectedCapType.value; + if (selectedCapType && selectedCapType.value) { + let selectedCapabilityTypeObj: CapabilityTypeModel = this.input.capabilityTypesList.find(capType => capType.toscaPresentation.type === selectedCapType.value); + this.capabilityData.description = selectedCapabilityTypeObj.toscaPresentation.description; + this.capabilityData.validSourceTypes = selectedCapabilityTypeObj.toscaPresentation.validTargetTypes; + this.capabilityData.properties = _.forEach( + _.toArray(selectedCapabilityTypeObj.properties), + prop => prop.uniqueId = null //a requirement for the BE + ); + } + this.validityChanged(); + } + + validityChanged = () => { + let validState = this.checkFormValidForSubmit(); + this.onValidationChange.next(validState); + } + +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilityEditor/capabilities-editor.module.ts b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilityEditor/capabilities-editor.module.ts new file mode 100644 index 0000000000..38b104a0f6 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/capabilities/capabilityEditor/capabilities-editor.module.ts @@ -0,0 +1,29 @@ +import {NgModule} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {CapabilitiesEditorComponent} from './capabilities-editor.component'; +import {FormsModule} from '@angular/forms'; +import {FormElementsModule} from 'app/ng2/components/ui/form-components/form-elements.module'; +import {UiElementsModule} from 'app/ng2/components/ui/ui-elements.module'; +import {TranslateModule} from 'app/ng2/shared/translator/translate.module'; +import {SdcUiComponentsModule} from 'onap-ui-angular'; +// import {SdcUiComponentsModule} from "sdc-ui/lib/angular/index"; + +@NgModule({ + declarations: [ + CapabilitiesEditorComponent + ], + imports: [CommonModule, + FormsModule, + FormElementsModule, + UiElementsModule, + TranslateModule, + SdcUiComponentsModule + ], + exports: [], + entryComponents: [ + CapabilitiesEditorComponent + ], + providers: [] +}) +export class CapabilitiesEditorModule { +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.component.html b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.component.html new file mode 100644 index 0000000000..73e0ae52ae --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.component.html @@ -0,0 +1,21 @@ +
+
+ Add Requirement + Add Capability + + + + +
+ + +
+
+ +
+
+
+
\ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.component.less b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.component.less new file mode 100644 index 0000000000..f3d39cacd6 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.component.less @@ -0,0 +1,19 @@ +.req-and-cap-filter { + width: 336px; + float: right; + margin-right: 10px; +} + +.addTitle { + float: right; + text-transform: uppercase; + font-family: OpenSans-Semibold, sans-serif; + color: #009fdb; + cursor: pointer; +} + +:host ::ng-deep .sdc-tabs { + .sdc-tab-content { + margin-top: 0; + } +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.component.spec.ts b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.component.spec.ts new file mode 100644 index 0000000000..b7fad045d3 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.component.spec.ts @@ -0,0 +1,127 @@ +import {async, ComponentFixture, TestBed} from "@angular/core/testing"; +import { NO_ERRORS_SCHEMA} from "@angular/core"; +import {ConfigureFn, configureTests} from "../../../../../jest/test-config.helper"; + +import {Observable} from "rxjs/Observable"; +import {NgxDatatableModule} from "@swimlane/ngx-datatable"; +import {SdcUiServices, SdcUiCommon} from "onap-ui-angular"; +import 'rxjs/add/observable/of'; +import {ReqAndCapabilitiesComponent} from "./req-and-capabilities.component"; +import {ReqAndCapabilitiesService} from "./req-and-capabilities.service"; +import {WorkspaceService} from "../workspace.service"; +import { + capabilitiesMock, + filterRequirmentsMock, + requirementMock +} from "../../../../../jest/mocks/req-and-capabilities.mock"; +import {ComponentMetadata} from "../../../../models/component-metadata"; +import { TopologyTemplateService } from "../../../services/component-services/topology-template.service"; +import {EventListenerService} from "../../../../services/event-listener-service"; + +describe('req and capabilities component', () => { + + let fixture: ComponentFixture; + let workspaceServiceMock: Partial; + let loaderServiceMock: Partial; + let topologyTemplateServiceMock: Partial; + let createDynamicComponentServiceMock: Partial + let reqAndCapabilitiesService: Partial; + let modalService: Partial; + let eventListenerService: Partial; + + + + beforeEach( + async(() => { + + workspaceServiceMock = { + metadata: new ComponentMetadata() + }; + + topologyTemplateServiceMock = { + getRequirementsAndCapabilitiesWithProperties: jest.fn().mockImplementation(() => + Observable.of({requirements: {'tosca.requirements.Node': requirementMock}, + capabilities: {'tosca.capabilities.Node': capabilitiesMock}})) + }; + + loaderServiceMock = { + activate : jest.fn(), + deactivate: jest.fn() + } + createDynamicComponentServiceMock = { + insertComponentDynamically: jest.fn() + } + + const configure: ConfigureFn = testBed => { + testBed.configureTestingModule({ + declarations: [ReqAndCapabilitiesComponent], + imports: [NgxDatatableModule], + schemas: [NO_ERRORS_SCHEMA], + providers: [ + { provide: WorkspaceService, useValue: workspaceServiceMock }, + { provide: SdcUiServices.LoaderService, useValue: loaderServiceMock }, + { provide: TopologyTemplateService, useValue: topologyTemplateServiceMock }, + { provide: SdcUiServices.CreateDynamicComponentService, useValue: createDynamicComponentServiceMock }, + { provide: ReqAndCapabilitiesService, useValue: reqAndCapabilitiesService }, + { provide: SdcUiServices.ModalService, useValue: modalService }, + { provide: EventListenerService, useValue: eventListenerService } + ], + }); + }; + configureTests(configure).then(testBed => { + fixture = testBed.createComponent(ReqAndCapabilitiesComponent); + }); + }) + ); + + it('should see exactly 2 requirement in requirements table when call initCapabilitiesAndRequirements and meta data requirements null', () => { + workspaceServiceMock.metadata.requirements = null; + fixture.componentInstance.initCapabilitiesAndRequirements(); + expect(workspaceServiceMock.metadata.requirements["tosca.requirements.Node"].length).toBe(3); + }); + it('should see exactly 2 capabilities in capabilities table when call initCapabilitiesAndRequirements and meta data capabilities null', () => { + workspaceServiceMock.metadata.capabilities = null; + fixture.componentInstance.initCapabilitiesAndRequirements(); + expect(workspaceServiceMock.metadata.capabilities["tosca.capabilities.Node"].length).toBe(2); + }); + + it('capabilities array papulated when call populateReqOrCap with capabilities', () => { + workspaceServiceMock.metadata.capabilities = {"tosca.capabilities.Node": capabilitiesMock, "tosca.capabilities.Scalable": capabilitiesMock}; + fixture.componentInstance.populateReqOrCap("capabilities"); + expect(fixture.componentInstance.capabilities.length).toBe(4); + }); + + it('create requirements component when call loadReqOrCap with true', () => { + createDynamicComponentServiceMock.insertComponentDynamically.mockImplementation(() => { return {instance: {requirements: requirementMock}}}); + fixture.componentInstance.requirements = requirementMock; + fixture.componentInstance.loadReqOrCap(true); + expect(fixture.componentInstance.instanceRef.instance.requirements.length).toEqual(3); + }); + + it('create capabilities component when call loadReqOrCap with false', () => { + fixture.componentInstance.instanceRef = {instance: {requirements: null}}; + createDynamicComponentServiceMock.insertComponentDynamically.mockImplementation(() => { return {instance: {capabilities: capabilitiesMock}}}); + fixture.componentInstance.capabilities = capabilitiesMock; + fixture.componentInstance.requirementsUI = filterRequirmentsMock; + let event = { + target : { + value : 'root' + } + } + fixture.componentInstance.updateFilter(event); + expect(fixture.componentInstance.instanceRef.instance.requirements.length).toBe(1); + }); + + it('should filter 1 capabilities when searching and call updateFilter function and instanceRef is capabilities component', () => { + fixture.componentInstance.instanceRef = {instance: {capabilities: null}}; + fixture.componentInstance.capabilities = capabilitiesMock; + fixture.componentInstance.selectTabName = 'CAPABILITIES'; + let event = { + target : { + value : '1source' + } + } + fixture.componentInstance.updateFilter(event); + expect(fixture.componentInstance.instanceRef.instance.capabilities[0].type).toBe("tosca.capabilities.Node"); + }); +}); diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.component.ts b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.component.ts new file mode 100644 index 0000000000..69999bfb86 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.component.ts @@ -0,0 +1,229 @@ +import { Component, ComponentRef, OnInit, ViewChild, ViewContainerRef } from '@angular/core'; +import * as _ from 'lodash'; +import { SdcUiServices } from 'onap-ui-angular'; +import { Capability, CapabilityUI } from '../../../../models/capability'; +import { Requirement, RequirementUI } from '../../../../models/requirement'; +import { TopologyTemplateService } from '../../../services/component-services/topology-template.service'; +import { ComponentGenericResponse } from '../../../services/responses/component-generic-response'; +import { WorkspaceService } from '../workspace.service'; +import { CapabilitiesComponent } from './capabilities/capabilities.component'; +import { RequirmentsComponent } from './requirements/requirments.components'; +import {ReqAndCapabilitiesService} from "./req-and-capabilities.service"; +import {CapabilitiesEditorComponent} from "./capabilities/capabilityEditor/capabilities-editor.component"; +import {ModalComponent} from "onap-ui-angular/dist/modals/modal.component"; +import {EventListenerService} from "../../../../services/event-listener-service"; +import {RequirementsEditorComponent} from "./requirements/requirementEditor/requirements-editor.component"; + +@Component({ + selector: 'req-and-capabilities', + templateUrl: './req-and-capabilities.component.html', + styleUrls: ['./req-and-capabilities.component.less'] +}) +export class ReqAndCapabilitiesComponent implements OnInit { + + @ViewChild('requirmentsContainer', { read: ViewContainerRef }) requirmentsContainer: ViewContainerRef; + @ViewChild('capabilitiesContainer', { read: ViewContainerRef }) capabilitiesContainer: ViewContainerRef; + private requirements: Requirement[] = []; + private requirementsUI: RequirementUI[] = []; + private capabilities: Capability[] = []; + private selectTabName: string = 'REQUIREMENTS'; + private notEmptyTable: boolean = true; + private instanceRef: ComponentRef; + private customModalInstance: ModalComponent; + readonly INPUTS_FOR_CAPABILITIES: string = 'INPUTS_FOR_CAPABILITIES'; + readonly INPUTS_FOR_REQUIREMENTS: string = 'INPUTS_FOR_REQUIREMENTS'; + + constructor(private workspaceService: WorkspaceService, + private loaderService: SdcUiServices.LoaderService, + private topologyTemplateService: TopologyTemplateService, + private createDynamicComponentService: SdcUiServices.CreateDynamicComponentService, + private reqAndCapabilitiesService : ReqAndCapabilitiesService, + private modalService: SdcUiServices.ModalService, + private eventListenerService: EventListenerService) { + } + + ngOnInit(): void { + this.initCapabilitiesAndRequirements(); + + this.eventListenerService.registerObserverCallback('CAPABILITIES_UPDATED', () => { + this.loadReqOrCap(); + }); + + this.eventListenerService.registerObserverCallback('REQUIREMENTS_UPDATED', () => { + this.loadReqOrCap(); + }); + } + + + + private initCapabilitiesAndRequirements(): void { + if (!this.workspaceService.metadata.capabilities || !this.workspaceService.metadata.requirements) { + this.loaderService.activate(); + this.topologyTemplateService.getRequirementsAndCapabilitiesWithProperties + (this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId) + .subscribe((response: ComponentGenericResponse) => { + this.workspaceService.metadata.capabilities = response.capabilities; + this.workspaceService.metadata.requirements = response.requirements; + this.initReqOrCap(); + this.loaderService.deactivate(); + }, (error) => { + this.loaderService.deactivate(); + }); + } else { + this.initReqOrCap(); + } + } + + private initReqOrCap() { + this.populateReqOrCap('requirements'); + this.extendRequirementsToRequiremnetsUI(this.requirements); + this.populateReqOrCap('capabilities'); + this.loadReqOrCap(); + } + + private populateReqOrCap(instanceName: string) { + _.forEach(this.workspaceService.metadata[instanceName], (concatArray: any[], name) => { + this[instanceName] = this[instanceName].concat(concatArray); + }); + } + + private updateFilter(event) { + const val = event.target.value.toLowerCase(); + if (this.selectTabName === 'REQUIREMENTS') { + this.instanceRef.instance.requirements = this.requirementsUI.filter((req: Requirement) => { + return !val || this.filterRequirments(req, val); + }); + } else { + this.instanceRef.instance.capabilities = this.capabilities.filter((cap: Capability) => { + return !val || this.filterCapabilities(cap, val); + }); + } + + } + + private selectTab($event) { + this.selectTabName = $event.title.contains('Requirement') ? 'REQUIREMENTS' : 'CATPABILITIES'; + this.loadReqOrCap(); + } + + private async loadReqOrCap() { + if (this.instanceRef) { + this.instanceRef.destroy(); + } + + if (this.selectTabName === 'REQUIREMENTS') { + this.notEmptyTable = this.requirementsUI.length !== 0; + this.instanceRef = this.createDynamicComponentService. + insertComponentDynamically(RequirmentsComponent, {requirements: this.requirementsUI}, this.requirmentsContainer); + // TODO - Keep the initInputs, so it will be called only for the first time - no need to wait to thse API's every time that a user switches tab + await this.reqAndCapabilitiesService.initInputs(this.INPUTS_FOR_REQUIREMENTS); + } else { + this.notEmptyTable = this.capabilities.length !== 0; + this.instanceRef = this.createDynamicComponentService. + insertComponentDynamically(CapabilitiesComponent, {capabilities: this.capabilities}, this.capabilitiesContainer); + // TODO - Keep the initInputs, so it will be called only for the first time - no need to wait to thse API's every time that a user switches tab + await this.reqAndCapabilitiesService.initInputs(this.INPUTS_FOR_CAPABILITIES); + } + } + + private filterCapabilities(capability: Capability, val: string): boolean { + return _.includes([capability.name, capability.description, capability.validSourceTypes.join(), + capability.minOccurrences, capability.maxOccurrences].join('').toLowerCase(), val) || + (capability.type && capability.type.replace('tosca.capabilities.', '').toLowerCase().indexOf(val) !== -1); + } + + private filterRequirments(requirement: Requirement, val: string): boolean { + return _.includes([requirement.name, requirement.minOccurrences, requirement.maxOccurrences].join('').toLowerCase(), val) || + (requirement.capability && requirement.capability.substring('tosca.capabilities.'.length).toLowerCase().indexOf(val) !== -1) || + (requirement.node && requirement.node.substring('tosca.node.'.length).toLowerCase().indexOf(val) !== -1) || + (requirement.relationship && requirement.relationship.substring('tosca.relationship.'.length) + .toLowerCase().indexOf(val) !== -1); + } + + private addCapability() { + let modalConfig = { + size: 'md', + title: 'Add Capability', + type: 'custom', + buttons: [ + { + id: 'saveButton', + text: ('Create'), + size: "'x-small'", + callback: () => this.createCapability(), + closeModal: true + }, + {text: "Cancel", size: "'x-small'", closeModal: true}] + }; + let modalInputs = { + capabilityTypesList: this.reqAndCapabilitiesService.getCapabilityTypesList(), + }; + + this.customModalInstance = this.modalService.openCustomModal(modalConfig, CapabilitiesEditorComponent, {input: modalInputs}); + this.customModalInstance.innerModalContent.instance. + onValidationChange.subscribe((isValid) => this.customModalInstance.getButtonById('saveButton').disabled = !isValid); + } + + private createCapability() { + const capability = this.customModalInstance.innerModalContent.instance.capabilityData; + this.loaderService.activate(); + if (!capability.uniqueId) { + this.topologyTemplateService.createCapability(this.workspaceService.metadata.getTypeUrl(), this.workspaceService.metadata.uniqueId, capability).subscribe((result) => { + this.capabilities.unshift(new CapabilityUI(result[0], this.workspaceService.metadata.uniqueId)); + this.loadReqOrCap(); + this.loaderService.deactivate(); + }, () => { + this.loaderService.deactivate(); + }); + } + } + + private addRequiremnet () { + let modalConfig = { + size: 'md', + title: 'Add Requirement', + type: 'custom', + buttons: [ + { + id: 'saveButton', + text: ('Create'), + size: "'x-small'", + callback: () => this.createRequirement(), + closeModal: true + }, + {text: "Cancel", size: "'x-small'", closeModal: true}] + }; + let modalInputs = { + // requirement: req, + relationshipTypesList: this.reqAndCapabilitiesService.getRelationsShipeTypeList(), + nodeTypesList: this.reqAndCapabilitiesService.getNodeTypesList(), + capabilityTypesList: this.reqAndCapabilitiesService.getCapabilityTypesList(), + // isReadonly: this.$scope.isViewMode() || !this.$scope.isDesigner(), + }; + + this.customModalInstance = this.modalService.openCustomModal(modalConfig, RequirementsEditorComponent, {input: modalInputs}); + this.customModalInstance.innerModalContent.instance. + onValidationChange.subscribe((isValid) => this.customModalInstance.getButtonById('saveButton').disabled = !isValid); + } + + + private createRequirement() { + const requirement = this.customModalInstance.innerModalContent.instance.requirementData; + this.loaderService.activate(); + if (!requirement.uniqueId) { + this.topologyTemplateService.createRequirement(this.workspaceService.metadata.getTypeUrl(), this.workspaceService.metadata.uniqueId, requirement).subscribe(result => { + this.requirementsUI.unshift(new RequirementUI(result[0], this.workspaceService.metadata.uniqueId)); + this.loadReqOrCap(); + this.loaderService.deactivate(); + }, () => { + this.loaderService.deactivate(); + }); + } + } + + private extendRequirementsToRequiremnetsUI(requirements: Requirement[]) { + this.requirements.map((requirement) => { + this.requirementsUI.push(new RequirementUI(requirement, this.workspaceService.metadata.uniqueId)); + }); + } +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.module.ts b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.module.ts new file mode 100644 index 0000000000..aacb3a5bd1 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.module.ts @@ -0,0 +1,49 @@ +import {NgModule} from "@angular/core"; +import {SdcUiComponentsModule} from "onap-ui-angular"; + +import {NgxDatatableModule} from "@swimlane/ngx-datatable"; +import { ReqAndCapabilitiesComponent } from "./req-and-capabilities.component"; +import { CommonModule } from "@angular/common"; + +import {RequirmentsComponent } from "./requirements/requirments.components"; +import { CapabilitiesComponent } from "./capabilities/capabilities.component"; +import { CapabilitiesPropertiesComponent } from "./capabilities/capabilities-properties/capabilities-properties"; +import {ReqAndCapabilitiesService} from "./req-and-capabilities.service"; +import {RequirementsEditorComponent} from "./requirements/requirementEditor/requirements-editor.component"; +import {CapabilitiesEditorComponent} from "./capabilities/capabilityEditor/capabilities-editor.component"; +import {TranslateModule} from "../../../shared/translator/translate.module"; +import {ToscaTypesServiceNg2} from "../../../services/tosca-types.service"; + +@NgModule({ + declarations: [ + ReqAndCapabilitiesComponent, + CapabilitiesComponent, + RequirmentsComponent, + CapabilitiesPropertiesComponent, + RequirementsEditorComponent, + CapabilitiesEditorComponent + ], + imports: [ + CommonModule, + SdcUiComponentsModule, + NgxDatatableModule, + TranslateModule + ], + exports: [ + ReqAndCapabilitiesComponent, + CapabilitiesComponent, + RequirmentsComponent, + CapabilitiesPropertiesComponent + ], + entryComponents: [ + ReqAndCapabilitiesComponent, + CapabilitiesComponent, + RequirmentsComponent, + CapabilitiesPropertiesComponent, + RequirementsEditorComponent, + CapabilitiesEditorComponent + ], + providers: [ ReqAndCapabilitiesService] +}) +export class reqAndCapabilitiesModule { +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.service.ts b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.service.ts new file mode 100644 index 0000000000..470aac75a6 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/req-and-capabilities.service.ts @@ -0,0 +1,80 @@ +import { Injectable } from "@angular/core"; +import { TopologyTemplateService } from "../../../services/component-services/topology-template.service"; +import { Store } from "@ngxs/store"; +import { SdcUiServices } from "onap-ui-angular"; +import { CapabilityTypeModel } from "../../../../models/capability-types"; +import { RelationshipTypeModel } from "../../../../models/relationship-types"; +import { NodeTypeModel } from "../../../../models/node-types"; +import { WorkspaceService } from "../workspace.service"; +import { ToscaTypesServiceNg2 } from "../../../services/tosca-types.service"; + + + +@Injectable() +export class ReqAndCapabilitiesService { + + private capabilityTypesList: CapabilityTypeModel[]; + private relationshipTypesList: RelationshipTypeModel[]; + private nodeTypesList: NodeTypeModel[]; + private capabilitiesListUpdated: boolean = false; + private requirementsListUpdated: boolean = false; + private nodeTypeListUpdated: boolean = false; + + readonly INPUTS_FOR_REQUIREMENTS: string = 'INPUTS_FOR_REQUIREMENTS'; + readonly INPUTS_FOR_CAPABILITIES: string = 'INPUTS_FOR_CAPABILITIES'; + + constructor( + private workspaceService: WorkspaceService, + private modalService: SdcUiServices.ModalService, + private loaderService: SdcUiServices.LoaderService, + private topologyTemplateService: TopologyTemplateService, + private store: Store, + private toscaTypesServiceNg2: ToscaTypesServiceNg2){} + + public isViewOnly = (): boolean => { + return this.store.selectSnapshot((state) => state.workspace.isViewOnly); + } + + public isDesigner = (): boolean => { + return this.store.selectSnapshot((state) => state.workspace.isDesigner); + } + + public async initInputs(initInputsFor: string) { + + if (!this.capabilitiesListUpdated){ + // -- COMMON for both -- + this.capabilityTypesList = []; + let capabilityTypesResult = await this.toscaTypesServiceNg2.fetchCapabilityTypes(); + Object.keys(capabilityTypesResult).forEach(key => {this.capabilityTypesList.push(capabilityTypesResult[key])}) + this.capabilitiesListUpdated = true; + } + + if (initInputsFor === 'INPUTS_FOR_REQUIREMENTS') { + if (!this.requirementsListUpdated){ + this.relationshipTypesList = []; + let relationshipTypesResult = await this.toscaTypesServiceNg2.fetchRelationshipTypes(); + Object.keys(relationshipTypesResult).forEach(key => {this.relationshipTypesList.push(relationshipTypesResult[key])}); + this.requirementsListUpdated = true; + } + + if (!this.nodeTypeListUpdated){ + this.nodeTypesList = []; + let nodeTypesResult = await this.toscaTypesServiceNg2.fetchNodeTypes(); + Object.keys(nodeTypesResult).forEach(key => {this.nodeTypesList.push(nodeTypesResult[key])}) + this.nodeTypeListUpdated = true; + } + } + } + + getCapabilityTypesList() { + return this.capabilityTypesList; + } + + getRelationsShipeTypeList() { + return this.relationshipTypesList; + } + + getNodeTypesList() { + return this.nodeTypesList; + } +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirementEditor/requirements-editor.component.html b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirementEditor/requirements-editor.component.html new file mode 100644 index 0000000000..330680d3ed --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirementEditor/requirements-editor.component.html @@ -0,0 +1,91 @@ +
+
+
+
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+ + + + +
+ +
+
+
+
+
\ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirementEditor/requirements-editor.component.less b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirementEditor/requirements-editor.component.less new file mode 100644 index 0000000000..6e50eb79f5 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirementEditor/requirements-editor.component.less @@ -0,0 +1,35 @@ +@import '../../../../../../../assets/styles/variables.less'; + +.requirement-editor { + .i-sdc-form-content-requirement-content { + padding: 10px 25px; + + .group-with-border { + margin: 25px 0; + padding: 15px 0; + border-top: 1px solid @tlv_color_u; + border-bottom: 1px solid @tlv_color_u; + .content-row:not(:last-of-type) { + padding-bottom: 13px; + } + } + + .occurrences-label { + font-family: @font-opensans-bold; + margin-bottom: 19px; + } + .occurrences-section, /deep/ .max-occurrences-value { + display: flex; + .min-occurrences-value { + padding-right: 30px; + } + .unbounded-value { + padding-top: 7px; + padding-right: 20px; + .sdc-checkbox__label { + text-transform: capitalize; + } + } + } + } +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirementEditor/requirements-editor.component.ts b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirementEditor/requirements-editor.component.ts new file mode 100644 index 0000000000..2c5c96f3da --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirementEditor/requirements-editor.component.ts @@ -0,0 +1,90 @@ +import {Component} from '@angular/core'; +import {ServiceServiceNg2} from "app/ng2/services/component-services/service.service"; +import {Requirement, RelationshipTypeModel, NodeTypeModel, CapabilityTypeModel} from 'app/models'; +import {TranslateService} from 'app/ng2/shared/translator/translate.service'; +import {DropdownValue} from "app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component"; +import {Subject} from "rxjs"; + +@Component({ + selector: 'requirements-editor', + templateUrl: 'requirements-editor.component.html', + styleUrls: ['requirements-editor.component.less'], + providers: [ServiceServiceNg2, TranslateService] +}) + +export class RequirementsEditorComponent { + + input: { + requirement: Requirement, + relationshipTypesList: Array; + nodeTypesList: Array; + capabilityTypesList: Array; + isReadonly: boolean; + }; + requirementData: Requirement; + capabilityTypesMappedList: Array; + relationshipTypesMappedList: Array; + nodeTypesMappedList: Array; + isUnboundedChecked: boolean; + isReadonly: boolean; + translatedUnboundTxt: string; + + public onValidationChange: Subject = new Subject(); + + constructor(private translateService: TranslateService) { + } + + ngOnInit() { + this.requirementData = new Requirement(this.input.requirement); + this.requirementData.minOccurrences = this.requirementData.minOccurrences || 0; + this.translatedUnboundTxt = ''; + this.capabilityTypesMappedList = _.map(this.input.capabilityTypesList, capType => new DropdownValue(capType.toscaPresentation.type, capType.toscaPresentation.type)); + this.relationshipTypesMappedList = _.map(this.input.relationshipTypesList, rType => new DropdownValue(rType.toscaPresentation.type, rType.toscaPresentation.type)); + this.nodeTypesMappedList = _.map(this.input.nodeTypesList, nodeType => { + return new DropdownValue( + nodeType.componentMetadataDefinition.componentMetadataDataDefinition.toscaResourceName, + nodeType.componentMetadataDefinition.componentMetadataDataDefinition.toscaResourceName) + }); + this.translateService.languageChangedObservable.subscribe(lang => { + this.translatedUnboundTxt = this.translateService.translate('REQ_CAP_OCCURRENCES_UNBOUNDED'); + this.requirementData.maxOccurrences = this.requirementData.maxOccurrences || this.translatedUnboundTxt; + this.isUnboundedChecked = this.requirementData.maxOccurrences === this.translatedUnboundTxt; + }); + this.isReadonly = this.input.isReadonly; + this.validityChanged(); + } + + onUnboundedChanged() { + this.isUnboundedChecked = !this.isUnboundedChecked; + this.requirementData.maxOccurrences = this.isUnboundedChecked ? this.translatedUnboundTxt : null; + this.validityChanged(); + } + + onCapabilityChanged(selectedCapability: DropdownValue) { + this.requirementData.capability = selectedCapability && selectedCapability.value; + this.validityChanged(); + } + + onNodeChanged(selectedNode: DropdownValue) { + this.requirementData.node = selectedNode && selectedNode.value; + } + + onRelationshipChanged(selectedRelationship: DropdownValue) { + this.requirementData.relationship = selectedRelationship && selectedRelationship.value; + } + + checkFormValidForSubmit() { + return this.requirementData.name && this.requirementData.name.length && + this.requirementData.capability && this.requirementData.capability.length && !_.isEqual(this.requirementData.minOccurrences, "") && this.requirementData.minOccurrences >= 0 && + ( + this.isUnboundedChecked || + (this.requirementData.maxOccurrences && (this.requirementData.minOccurrences <= parseInt(this.requirementData.maxOccurrences))) + ); + } + + validityChanged = () => { + let validState = this.checkFormValidForSubmit(); + this.onValidationChange.next(validState); + } + +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirementEditor/requirements-editor.module.ts b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirementEditor/requirements-editor.module.ts new file mode 100644 index 0000000000..b1d8db54aa --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirementEditor/requirements-editor.module.ts @@ -0,0 +1,28 @@ +import {NgModule} from "@angular/core"; +import {CommonModule} from "@angular/common"; +import {RequirementsEditorComponent} from "./requirements-editor.component"; +import {FormsModule} from "@angular/forms"; +// import {FormElementsModule} from "../../../components/ui/form-components/form-elements.module"; +import {TranslateModule} from 'app/ng2/shared/translator/translate.module'; +import {SdcUiComponentsModule} from "onap-ui-angular/"; +import {FormElementsModule} from 'app/ng2/components/ui/form-components/form-elements.module'; +// import {SdcUiComponentsModule} from "sdc-ui/lib/angular/index"; + +@NgModule({ + declarations: [ + RequirementsEditorComponent + ], + imports: [CommonModule, + FormsModule, + FormElementsModule, + TranslateModule, + SdcUiComponentsModule + ], + exports: [], + entryComponents: [ + RequirementsEditorComponent + ], + providers: [] +}) +export class RequirementsEditorModule { +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirements.component.less b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirements.component.less new file mode 100644 index 0000000000..19f1c9b55a --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirements.component.less @@ -0,0 +1,4 @@ +/deep/ .importedFromFile { + background-color: #f8f8f8; + color: #959595; + } \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirments.components.html b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirments.components.html new file mode 100644 index 0000000000..7606ed189a --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirments.components.html @@ -0,0 +1,38 @@ +
+ + + + {{row.name}} + + + + + {{row.capability ? row.capability.substring("tosca.capabilities.".length) : ''}} + + + + + {{row.node ? row.node.substring("tosca.nodes.".length) : ''}} + + + + + {{row.relationship ? row.relationship.substring("tosca.relationships.".length): ''}} + + + + + + + + {{row.minOccurrences}},{{row.maxOccurrences}} + + + +
\ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirments.components.ts b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirments.components.ts new file mode 100644 index 0000000000..b65489ce4e --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/req-and-capabilities/requirements/requirments.components.ts @@ -0,0 +1,103 @@ +import {Input, Component, OnInit} from "@angular/core"; +import {Requirement, RequirementUI} from "../../../../../models/requirement"; +import {RequirementsEditorComponent} from "./requirementEditor/requirements-editor.component"; +import {WorkspaceService} from "../../workspace.service"; +import {TopologyTemplateService} from "../../../../services/component-services/topology-template.service"; +import {ReqAndCapabilitiesService} from "../req-and-capabilities.service"; +import {EventListenerService} from "../../../../../services/event-listener-service"; +import {ModalComponent} from "onap-ui-angular/dist/modals/modal.component"; +import {SdcUiServices} from "onap-ui-angular"; +import sortedIndexBy = require("lodash/sortedIndexBy"); + +@Component({ + selector: 'requirments', + templateUrl: './requirments.components.html', + styleUrls: ['../../../../../../assets/styles/table-style.less', './requirements.component.less'] +}) + + + +export class RequirmentsComponent implements OnInit { + @Input() public requirements: Array; + private customModalInstance: ModalComponent; + + constructor( + private workspaceService: WorkspaceService, + private loaderService: SdcUiServices.LoaderService, + private topologyTemplateService: TopologyTemplateService, + private reqAndCapabilitiesService : ReqAndCapabilitiesService, + private modalService: SdcUiServices.ModalService, + private eventListenerService: EventListenerService) { + } + + + ngOnInit(): void { + let isCreatedManually: RequirementUI[] = []; + let isImportedFromFile: RequirementUI[] = []; + + isCreatedManually = this.requirements.filter((requirement) => requirement.isCreatedManually); + isImportedFromFile = this.requirements.filter((requirement) => !requirement.isCreatedManually); + + this.requirements = []; + + isCreatedManually.map((requirement) => this.requirements.push(requirement)); + isImportedFromFile.map((requirement) => this.requirements.push(requirement)); + + } + + + + editRequirement(req) { + + let modalConfig = { + size: 'md', + title: 'Update Requirement', + type: 'custom', + buttons: [ + { + id: 'saveButton', + text: ('Update'), + size: "'x-small'", + callback: () => this.updateRequirement(), + closeModal: true + }, + {text: "Cancel", size: "'x-small'", closeModal: true}] + }; + let modalInputs = { + requirement: req, + relationshipTypesList: this.reqAndCapabilitiesService.getRelationsShipeTypeList(), + nodeTypesList: this.reqAndCapabilitiesService.getNodeTypesList(), + capabilityTypesList: this.reqAndCapabilitiesService.getCapabilityTypesList(), + // isReadonly: this.$scope.isViewMode() || !this.$scope.isDesigner(), + }; + + this.customModalInstance = this.modalService.openCustomModal(modalConfig, RequirementsEditorComponent, {input: modalInputs}); + this.customModalInstance.innerModalContent.instance. + onValidationChange.subscribe((isValid) => this.customModalInstance.getButtonById('saveButton').disabled = !isValid); + + } + + private updateRequirement() { + const requirement = this.customModalInstance.innerModalContent.instance.requirementData; + this.loaderService.activate(); + if (requirement.uniqueId) { + this.topologyTemplateService.updateRequirement(this.workspaceService.metadata.getTypeUrl(), this.workspaceService.metadata.uniqueId, requirement).subscribe(result => { + let index = this.requirements.findIndex(req => result[0].uniqueId === req.uniqueId); + this.requirements[index] = new RequirementUI(result[0], this.workspaceService.metadata.uniqueId); + this.eventListenerService.notifyObservers('REQUIREMENTS_UPDATED'); + this.loaderService.deactivate(); + }, () => { + this.loaderService.deactivate(); + }); + } + } + + getRowClass(row) { + if (!row.isCreatedManually) { + return { + 'importedFromFile': true + }; + } + } + +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/__snapshots__/tosca-artifact-page.spec.ts.snap b/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/__snapshots__/tosca-artifact-page.spec.ts.snap new file mode 100644 index 0000000000..14146d51d2 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/__snapshots__/tosca-artifact-page.spec.ts.snap @@ -0,0 +1,35 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`tosca artifacts page should match current snapshot of tosca artifact pages component 1`] = ` + +
+ +
+ + + + + + + + + +
+
+
+
+`; diff --git a/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/tosca-artifact-page.component.html b/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/tosca-artifact-page.component.html new file mode 100644 index 0000000000..fece92ee37 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/tosca-artifact-page.component.html @@ -0,0 +1,50 @@ +
+ + + +
Label: {{row.artifactLabel}}
+
UUID: {{row.artifactUUID}}
+
Description: {{row.description}}
+
+
+ + +
+ + {{row.artifactDisplayName }} +
+
+
+ + + {{row.artifactType}} + + + + + {{ row.artifactVersion }} + + + + +
+ +
+
+
+
+
\ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/tosca-artifact-page.component.less b/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/tosca-artifact-page.component.less new file mode 100644 index 0000000000..9c5dd47585 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/tosca-artifact-page.component.less @@ -0,0 +1,7 @@ +.tosca-artifact-page { + .download-artifact-button { + text-align: center; + padding-top: 4px; + + } +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/tosca-artifact-page.component.ts b/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/tosca-artifact-page.component.ts new file mode 100644 index 0000000000..e74e5db668 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/tosca-artifact-page.component.ts @@ -0,0 +1,46 @@ +import {Component, OnInit, ViewChild} from "@angular/core"; +import {WorkspaceService} from "../workspace.service"; +import {SdcUiServices} from "onap-ui-angular"; +import {ArtifactModel} from "../../../../models"; +import {Select, Store} from "@ngxs/store"; +import {WorkspaceState} from "../../../store/states/workspace.state"; +import * as _ from "lodash"; +import {ArtifactGroupType, COMPONENT_FIELDS} from "../../../../utils"; +import {GetArtifactsByTypeAction} from "../../../store/actions/artifacts.action"; +import {Observable} from "rxjs/index"; +import {ArtifactsState} from "../../../store/states/artifacts.state"; +import {ArtifactType} from "../../../../utils/constants"; +import {map} from "rxjs/operators"; + +@Component({ + selector: 'tosca-artifact-page', + + templateUrl: './tosca-artifact-page.component.html', + styleUrls: ['./tosca-artifact-page.component.less', '../../../../../assets/styles/table-style.less'] +}) +export class ToscaArtifactPageComponent implements OnInit { + + @Select(WorkspaceState.isViewOnly) isViewOnly$: boolean; + @ViewChild('toscaArtifactsTable') table: any; + public toscaArtifacts$: Observable; + public componentId: string; + public componentType:string; + + constructor(private serviceLoader: SdcUiServices.LoaderService, private workspaceService: WorkspaceService, private store: Store) { + } + + + ngOnInit(): void { + this.componentId = this.workspaceService.metadata.uniqueId; + this.componentType = this.workspaceService.metadata.componentType; + + this.store.dispatch(new GetArtifactsByTypeAction({componentType:this.componentType, componentId:this.componentId, artifactType:ArtifactGroupType.TOSCA})); + this.toscaArtifacts$ = this.store.select(ArtifactsState.getArtifactsByType).pipe(map(filterFn => filterFn(ArtifactGroupType.TOSCA))); + } + + onActivate(event) { + if(event.type === 'click'){ + this.table.rowDetail.toggleExpandRow(event.row); + } + } +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/tosca-artifact-page.module.ts b/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/tosca-artifact-page.module.ts new file mode 100644 index 0000000000..00c7b0b371 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/tosca-artifact-page.module.ts @@ -0,0 +1,28 @@ +import {CommonModule} from "@angular/common"; +import {NgModule} from "@angular/core"; +import {SdcUiComponentsModule} from "onap-ui-angular"; +import {GlobalPipesModule} from "../../../pipes/global-pipes.module"; +import {NgxDatatableModule} from "@swimlane/ngx-datatable"; +import {ToscaArtifactPageComponent} from "./tosca-artifact-page.component"; +import {UiElementsModule} from "../../../components/ui/ui-elements.module"; + +@NgModule({ + declarations: [ + ToscaArtifactPageComponent + ], + imports: [ + CommonModule, + SdcUiComponentsModule, + NgxDatatableModule, + UiElementsModule + ], + exports: [ + ToscaArtifactPageComponent + ], + entryComponents: [ + ToscaArtifactPageComponent + ], + +}) +export class ToscaArtifactPageModule { +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/tosca-artifact-page.spec.ts b/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/tosca-artifact-page.spec.ts new file mode 100644 index 0000000000..af3558e15b --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/tosca-artifacts/tosca-artifact-page.spec.ts @@ -0,0 +1,71 @@ +import {async, ComponentFixture, TestBed} from "@angular/core/testing"; +import {NO_ERRORS_SCHEMA} from "@angular/core"; +import {ToscaArtifactPageComponent} from "./tosca-artifact-page.component"; +import {ConfigureFn, configureTests} from "../../../../../jest/test-config.helper"; +import {NgxDatatableModule} from "@swimlane/ngx-datatable"; +import {WorkspaceService} from "../workspace.service"; +import {SdcUiServices} from "onap-ui-angular"; +import {TopologyTemplateService} from "../../../services/component-services/topology-template.service"; +import {Observable} from "rxjs/Observable"; +import {ComponentMetadata} from "../../../../models/component-metadata"; +import 'rxjs/add/observable/of'; +import {NgxsModule, Store} from "@ngxs/store"; +import {ArtifactsState} from "../../../store/states/artifacts.state"; +import {toscaArtifactMock} from "../../../../../jest/mocks/artifacts-mock"; + +describe('tosca artifacts page', () => { + + let fixture: ComponentFixture; + let topologyTemplateServiceMock: Partial; + let workspaceServiceMock: Partial; + let loaderServiceMock: Partial; + let store: Store; + + + beforeEach( + async(() => { + + topologyTemplateServiceMock = { + getArtifactsByType: jest.fn().mockImplementation((componentType, id, artifactType) => Observable.of(toscaArtifactMock)) + }; + workspaceServiceMock = {metadata: {uniqueId: 'service_unique_id', componentType: 'SERVICE'}} + + loaderServiceMock = { + activate : jest.fn(), + deactivate: jest.fn() + } + const configure: ConfigureFn = testBed => { + testBed.configureTestingModule({ + declarations: [ToscaArtifactPageComponent], + imports: [NgxDatatableModule, NgxsModule.forRoot([ArtifactsState])], + schemas: [NO_ERRORS_SCHEMA], + providers: [ + {provide: WorkspaceService, useValue: workspaceServiceMock}, + {provide: TopologyTemplateService, useValue: topologyTemplateServiceMock}, + {provide: SdcUiServices.LoaderService, useValue: loaderServiceMock } + ], + }); + }; + + configureTests(configure).then(testBed => { + fixture = testBed.createComponent(ToscaArtifactPageComponent); + store = testBed.get(Store); + }); + }) + ); + + it('should match current snapshot of tosca artifact pages component', () => { + expect(fixture).toMatchSnapshot(); + }); + + it('should see exactly 2 tosca artifacts', () => { + fixture.componentInstance.ngOnInit(); + fixture.componentInstance.toscaArtifacts$.subscribe((artifacts)=> { + expect(artifacts.length).toEqual(2); + }) + store.selectOnce(state => state.artifacts.toscaArtifacts).subscribe(artifacts => { + expect(artifacts.length).toEqual(9); + }); + }) + +}); \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pages/workspace/workspace-ng1-bridge-service.ts b/catalog-ui/src/app/ng2/pages/workspace/workspace-ng1-bridge-service.ts new file mode 100644 index 0000000000..3d93b459a2 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/workspace-ng1-bridge-service.ts @@ -0,0 +1,37 @@ +/** + * Created by ob0695 on 6/24/2018. + */ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +import {Store} from "@ngxs/store"; +import {Injectable} from "@angular/core"; +import {UpdateIsViewOnly} from "../../store/actions/workspace.action"; + +@Injectable() +export class WorkspaceNg1BridgeService { + + constructor(private store: Store) { + }; + + public updateIsViewOnly = (isViewOnly: boolean):void => { + this.store.dispatch(new UpdateIsViewOnly(isViewOnly)); + } + +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/workspace.component.ts b/catalog-ui/src/app/ng2/pages/workspace/workspace.component.ts new file mode 100644 index 0000000000..a209406a53 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/workspace.component.ts @@ -0,0 +1,3 @@ +/** + * Created by ob0695 on 6/11/2018. + */ diff --git a/catalog-ui/src/app/ng2/pages/workspace/workspace.module.ts b/catalog-ui/src/app/ng2/pages/workspace/workspace.module.ts new file mode 100644 index 0000000000..cb646379d2 --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/workspace.module.ts @@ -0,0 +1,50 @@ +/** + * Created by ob0695 on 6/4/2018. + */ +/** + * Created by ob0695 on 6/4/2018. + */ +import {NgModule} from "@angular/core"; +import {CompositionPageModule} from "../composition/composition-page.module"; + +import {NgxsModule} from "@ngxs/store"; +import {TopologyTemplateService} from "../../services/component-services/topology-template.service"; +import {WorkspaceState} from "../../store/states/workspace.state"; +import {WorkspaceService} from "./workspace.service"; +import {DeploymentPageModule} from "./deployment/deployment-page.module"; +import {ToscaArtifactPageModule} from "./tosca-artifacts/tosca-artifact-page.module"; +import {InformationArtifactPageModule} from "./information-artifact/information-artifact-page.module"; +import { reqAndCapabilitiesModule } from "./req-and-capabilities/req-and-capabilities.module"; +import {AttributesModule} from "./attributes/attributes.module"; +import {ArtifactsState} from "../../store/states/artifacts.state"; +import {InstanceArtifactsState} from "../../store/states/instance-artifacts.state"; +import {DeploymentArtifactsPageModule} from "./deployment-artifacts/deployment-artifacts-page.module"; +import { DistributionModule } from './disribution/distribution.module'; +import { ActivityLogModule } from './activity-log/activity-log.module'; + +@NgModule({ + declarations: [], + imports: [ + DeploymentPageModule, + CompositionPageModule, + AttributesModule, + reqAndCapabilitiesModule, + ToscaArtifactPageModule, + DeploymentArtifactsPageModule, + InformationArtifactPageModule, + DistributionModule, + ActivityLogModule, + NgxsModule.forFeature([WorkspaceState, ArtifactsState, InstanceArtifactsState]) + ], + + exports: [], + entryComponents: [], + providers: [TopologyTemplateService, WorkspaceService] +}) + +export class WorkspaceModule { + + constructor() { + + } +} diff --git a/catalog-ui/src/app/ng2/pages/workspace/workspace.service.ts b/catalog-ui/src/app/ng2/pages/workspace/workspace.service.ts new file mode 100644 index 0000000000..9f985016ec --- /dev/null +++ b/catalog-ui/src/app/ng2/pages/workspace/workspace.service.ts @@ -0,0 +1,70 @@ +/** + * Created by ob0695 on 6/5/2018. + */ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +/** + * Created by rc2122 on 5/23/2017. + */ +import { Injectable } from '@angular/core'; +import {WorkspaceMode, ComponentState, Role} from "../../../utils/constants"; +import {Component as TopologyTemplate, ComponentMetadata} from "app/models"; +import {CacheService} from "../../services/cache.service"; +import {IComponentMetadata} from "../../../models/component-metadata"; +import {ComponentType} from "../../../utils"; + +@Injectable() +export class WorkspaceService { + + public metadata:ComponentMetadata; + + constructor(private cacheService:CacheService) { + + } + + public setComponentMetadata = (metadata: ComponentMetadata) => { + this.metadata = metadata; + } + + public getMetadataType(): string { + switch (this.metadata.componentType) { + case ComponentType.SERVICE: + return ComponentType.SERVICE; + default: + return this.metadata.resourceType; + } + } + + public getComponentMode = (component:TopologyTemplate):WorkspaceMode => {//return if is edit or view for resource or service + let mode = WorkspaceMode.VIEW; + + let user = this.cacheService.get("user"); + if (component.lifecycleState === ComponentState.NOT_CERTIFIED_CHECKOUT && + component.lastUpdaterUserId === user.userId) { + if ((component.isService() || component.isResource()) && user.role == Role.DESIGNER) { + mode = WorkspaceMode.EDIT; + } + } + return mode; + } +} + + \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/pipes/entity-filter.pipe.ts b/catalog-ui/src/app/ng2/pipes/entity-filter.pipe.ts new file mode 100644 index 0000000000..af107ed006 --- /dev/null +++ b/catalog-ui/src/app/ng2/pipes/entity-filter.pipe.ts @@ -0,0 +1,151 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +import {Pipe, PipeTransform} from "@angular/core"; +import {Component, Resource} from "app/models"; +import {ComponentType} from "app/utils/constants"; + +export interface ISearchFilter { + [key:string]: string; +} + +export interface IEntityFilterObject { + // Types + selectedComponentTypes?:Array; + selectedResourceSubTypes?:Array; + // Categories + selectedCategoriesModel?:Array; + // Statuses + selectedStatuses?:Array; + // distributed + distributed?:Array; + // search + search?:ISearchFilter; + +} + +@Pipe({name: 'entity-filter'}) +export class EntityFilterPipe implements PipeTransform{ + constructor() { + } + + public static transform(components:Array, filter:IEntityFilterObject) { + let filteredComponents:Array = components; + + // filter by type + // -------------------------------------------------------------------------- + if ((filter.selectedComponentTypes && filter.selectedComponentTypes.length > 0) || (filter.selectedResourceSubTypes && filter.selectedResourceSubTypes.length > 0)) { + let filteredTypes = []; + angular.forEach(components, (component:Component):void => { + // Filter by component type + let typeLower:string = component.componentType.toLowerCase(); + let typeFirstCapital:string = typeLower.charAt(0).toUpperCase() + typeLower.slice(1); + if (filter.selectedComponentTypes.indexOf(typeFirstCapital) !== -1) { + filteredTypes.push(component); + } + + // Filter by resource sub type, only in case the resource checkbox was not selected (because in this case we already added all the components in above section). + if (component.isResource() && filter.selectedComponentTypes.indexOf("Resource") === -1 && filter.selectedResourceSubTypes.length > 0) { + //filteredComponents.pop(); // Remove the last inserted component. + let resource:Resource = component; + if (filter.selectedResourceSubTypes.indexOf(resource.getComponentSubType()) !== -1) { + filteredTypes.push(component); + } + } + }); + filteredComponents = filteredTypes; + } + + // filter by categories & subcategories & groupings + // -------------------------------------------------------------------------- + if (filter.selectedCategoriesModel && filter.selectedCategoriesModel.length > 0) { + let filteredCategories = []; + angular.forEach(filteredComponents, (component:Component):void => { + let componentCategory = component.categoryNormalizedName + + ((component.subCategoryNormalizedName) ? '.' + component.subCategoryNormalizedName : ''); + if (component.componentType === ComponentType.RESOURCE) { + componentCategory = 'resourceNewCategory.' + componentCategory; + } else if (component.componentType === ComponentType.SERVICE) { + componentCategory = 'serviceNewCategory.' + componentCategory; + } + if (filter.selectedCategoriesModel.indexOf(componentCategory) !== -1) { + filteredCategories.push(component); + } + }); + filteredComponents = filteredCategories; + } + + // filter by statuses + // -------------------------------------------------------------------------- + if (filter.selectedStatuses && filter.selectedStatuses.length > 0) { + + let filteredStatuses = []; + angular.forEach(filteredComponents, (component:Component):void => { + if (filter.selectedStatuses.indexOf(component.lifecycleState) > -1) { + filteredStatuses.push(component); + } + //if status DISTRIBUTED && CERTIFIED are selected the component will added in CERTIFIED status , not need to add twice + if (filter.selectedStatuses.indexOf('DISTRIBUTED') > -1 && !(filter.selectedStatuses.indexOf('CERTIFIED') > -1)) { + if (component.distributionStatus && component.distributionStatus.indexOf('DISTRIBUTED') > -1 && component.lifecycleState.indexOf('CERTIFIED') > -1) { + filteredStatuses.push(component); + } + } + }); + filteredComponents = filteredStatuses; + } + + // filter by statuses and distributed + // -------------------------------------------------------------------------- + if (filter.distributed != undefined && filter.distributed.length > 0) { + let filterDistributed:Array = filter.distributed; + let filteredDistributed = []; + angular.forEach(filteredComponents, (entity) => { + filterDistributed.forEach((distribute) => { + let distributeItem = distribute.split(','); + distributeItem.forEach((item) => { + if (item !== undefined && entity.distributionStatus === item) { + filteredDistributed.push(entity); + } + }) + }); + }); + filteredComponents = filteredDistributed; + } + + // filter by search + // -------------------------------------------------------------------------- + if (filter.search != undefined) { + Object.keys(filter.search).forEach((searchKey) => { + let searchVal = filter.search[searchKey]; + if (searchVal) { + searchVal = searchVal.toLowerCase(); + filteredComponents = filteredComponents.filter((component:Component) => + component[searchKey].toLowerCase().indexOf(searchVal) !== -1); + } + }); + } + + return filteredComponents; + } + + public transform(components:Array, filter:IEntityFilterObject) { + return EntityFilterPipe.transform(components, filter); + } +} diff --git a/catalog-ui/src/app/ng2/pipes/global-pipes.module.ts b/catalog-ui/src/app/ng2/pipes/global-pipes.module.ts index c44d71b30d..66f9518a47 100644 --- a/catalog-ui/src/app/ng2/pipes/global-pipes.module.ts +++ b/catalog-ui/src/app/ng2/pipes/global-pipes.module.ts @@ -26,7 +26,10 @@ import {GroupByPipe} from "./groupBy.pipe"; import {ResourceNamePipe} from "./resource-name.pipe"; import {NgModule} from "@angular/core"; import {SafeUrlSanitizerPipe} from "./safeUrlSanitizer.pipe"; -import {OrderByPipe} from "./orderBy.pipe"; +import {EntityFilterPipe} from "./entity-filter.pipe"; +import {KeyValuePipe} from "./key-value.pipe"; +import {PropertiesOrderByPipe} from "./properties-order-by.pipe"; +import {OrderByPipe} from "./order-by.pipe"; @NgModule({ declarations: [ @@ -36,6 +39,9 @@ import {OrderByPipe} from "./orderBy.pipe"; SafeUrlSanitizerPipe, SearchFilterPipe, ResourceNamePipe, + EntityFilterPipe, + KeyValuePipe, + PropertiesOrderByPipe, OrderByPipe ], exports: [ @@ -45,7 +51,20 @@ import {OrderByPipe} from "./orderBy.pipe"; SafeUrlSanitizerPipe, SearchFilterPipe, ResourceNamePipe, - OrderByPipe + EntityFilterPipe, + PropertiesOrderByPipe, + OrderByPipe, + KeyValuePipe + ], + providers: [ + ContentAfterLastDotPipe, + GroupByPipe, + KeysPipe, + SafeUrlSanitizerPipe, + SearchFilterPipe, + ResourceNamePipe, + EntityFilterPipe, + KeyValuePipe ] }) diff --git a/catalog-ui/src/app/ng2/pipes/groupBy.pipe.ts b/catalog-ui/src/app/ng2/pipes/groupBy.pipe.ts index 90dce23352..19811f2f08 100644 --- a/catalog-ui/src/app/ng2/pipes/groupBy.pipe.ts +++ b/catalog-ui/src/app/ng2/pipes/groupBy.pipe.ts @@ -26,6 +26,9 @@ import {Pipe, PipeTransform} from '@angular/core'; @Pipe({name: 'groupBy'}) export class GroupByPipe implements PipeTransform { transform(value: Array, field: string): Array { + if(!value) { + return null; + } const groupedObj = value.reduce((prev, cur)=> { if(!prev[cur[field]]) { prev[cur[field]] = [cur]; diff --git a/catalog-ui/src/app/ng2/pipes/key-value.pipe.ts b/catalog-ui/src/app/ng2/pipes/key-value.pipe.ts new file mode 100644 index 0000000000..4adb0b12f7 --- /dev/null +++ b/catalog-ui/src/app/ng2/pipes/key-value.pipe.ts @@ -0,0 +1,41 @@ +/** + * Created by ob0695 on 7/3/2018. + */ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +/** + * Created by rc2122 on 5/17/2017. + */ +import {Pipe, PipeTransform} from '@angular/core'; + +@Pipe({name: 'keyValue'}) +export class KeyValuePipe implements PipeTransform { + transform(value, field: string): Array { + if(!value) { + return null; + } + let keyValueObject = []; + for (let key in value) { + keyValueObject.push({key:key, value: value[key]}); + } + return keyValueObject; + } +} diff --git a/catalog-ui/src/app/ng2/pipes/keys.pipe.ts b/catalog-ui/src/app/ng2/pipes/keys.pipe.ts index 349e9334f7..f8663aca2e 100644 --- a/catalog-ui/src/app/ng2/pipes/keys.pipe.ts +++ b/catalog-ui/src/app/ng2/pipes/keys.pipe.ts @@ -23,6 +23,9 @@ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'keys'}) export class KeysPipe implements PipeTransform { transform(value, args:string[]) : any { + if(!value) { + return null; + } let keys = []; for (let key in value) { keys.push(key); diff --git a/catalog-ui/src/app/ng2/pipes/order-by.pipe.ts b/catalog-ui/src/app/ng2/pipes/order-by.pipe.ts new file mode 100644 index 0000000000..6dc5d47863 --- /dev/null +++ b/catalog-ui/src/app/ng2/pipes/order-by.pipe.ts @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 Huawei Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +import { Pipe, PipeTransform } from '@angular/core'; + +@Pipe({name: 'orderBy'}) +export class OrderByPipe implements PipeTransform { + transform(records: Array, args?: any): any { + if (!records || !args.path) { return records; } + let len = args.path.length; + return records.sort((itemIdx1, itemIdx2) => { + var i = 0; + while (i < len) { itemIdx1 = itemIdx1[args.path[i]]; itemIdx2 = itemIdx2[args.path[i]]; i++; } + // Order * (-1): We change our order + return itemIdx1 + "" > itemIdx2 + "" ? args.direction : args.direction * (- 1); + }) + }; +} diff --git a/catalog-ui/src/app/ng2/pipes/orderBy.pipe.ts b/catalog-ui/src/app/ng2/pipes/orderBy.pipe.ts deleted file mode 100644 index 4edbd60f60..0000000000 --- a/catalog-ui/src/app/ng2/pipes/orderBy.pipe.ts +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 Huawei Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -import { Pipe, PipeTransform } from '@angular/core'; - -@Pipe({ name: 'orderBy' }) -export class OrderByPipe implements PipeTransform { - transform(records: Array, args?: any): any { - if (!records || !args.path) return records; - let len = args.path.length; - return records.sort((itemIdx1, itemIdx2) => { - var i = 0; - while (i < len) { itemIdx1 = itemIdx1[args.path[i]]; itemIdx2 = itemIdx2[args.path[i]]; i++; } - // Order * (-1): We change our order - return itemIdx1 + "" > itemIdx2 + "" ? args.direction : args.direction * (- 1); - }) - }; -} diff --git a/catalog-ui/src/app/ng2/pipes/properties-order-by.pipe.ts b/catalog-ui/src/app/ng2/pipes/properties-order-by.pipe.ts new file mode 100644 index 0000000000..98debd28d9 --- /dev/null +++ b/catalog-ui/src/app/ng2/pipes/properties-order-by.pipe.ts @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 Huawei Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +import { Pipe, PipeTransform } from '@angular/core'; + +@Pipe({ name: 'propertiesOrderBy' }) +export class PropertiesOrderByPipe implements PipeTransform { + transform(records: Array, args?: any): any { + if (!records || !args.path) return records; + let len = args.path.length; + return records.sort((itemIdx1, itemIdx2) => { + var i = 0; + while (i < len) { itemIdx1 = itemIdx1[args.path[i]]; itemIdx2 = itemIdx2[args.path[i]]; i++; } + // Order * (-1): We change our order + return itemIdx1 + "" > itemIdx2 + "" ? args.direction : args.direction * (- 1); + }) + }; +} diff --git a/catalog-ui/src/app/ng2/pipes/resource-name.pipe.ts b/catalog-ui/src/app/ng2/pipes/resource-name.pipe.ts index fdf9526375..0fdbbcaade 100644 --- a/catalog-ui/src/app/ng2/pipes/resource-name.pipe.ts +++ b/catalog-ui/src/app/ng2/pipes/resource-name.pipe.ts @@ -20,15 +20,20 @@ import { Pipe, PipeTransform } from '@angular/core'; +import * as _ from 'lodash'; @Pipe({name: 'resourceName'}) export class ResourceNamePipe implements PipeTransform { + + public static getDisplayName (value:string): string { + const newName:string = + _.last(value.split(/tosca\.nodes\..*network\..*relationships\..*org\.openecomp\..*resource\.nfv\..*nodes\.module\..*cp\..*vl\./)); + return (newName) ? newName : value; + } + transform(value) : any { if (value) { - //newName = _.last(newName.split('.')); - const newName:string = - _.last(value.split(/tosca\.nodes\..*network\..*relationships\..*org\.openecomp\..*resource\.nfv\..*nodes\.module\..*cp\..*vl\./)); - return (newName) ? newName : value; + return ResourceNamePipe.getDisplayName(value); } } } diff --git a/catalog-ui/src/app/ng2/services/activity-log.service.ts b/catalog-ui/src/app/ng2/services/activity-log.service.ts new file mode 100644 index 0000000000..deabbee0bd --- /dev/null +++ b/catalog-ui/src/app/ng2/services/activity-log.service.ts @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +import { HttpClient } from '@angular/common/http'; +import { Inject, Injectable} from '@angular/core'; +import { Observable } from 'rxjs/Observable'; +import { Activity } from '../../models/activity'; +import { ServerTypeUrl } from '../../utils/constants'; +import { ISdcConfig, SdcConfigToken } from '../config/sdc-config.config'; +import { HttpHelperService } from './http-hepler.service'; + +@Injectable() +export class ActivityLogService { + url: string; + + constructor(private httpClient: HttpClient, @Inject(SdcConfigToken) private sdcConfig:ISdcConfig) { + this.url = this.sdcConfig.api.root + this.sdcConfig.api.GET_activity_log; + } + + public getActivityLog(componentType: string, uid: string): Observable { + + // Compose URL: audit-records/services_or_resources/uid + const url = HttpHelperService.replaceUrlParams(this.url, { + type: ServerTypeUrl.toServerTypeUrl(componentType), + id: uid + }); + + return this.httpClient.get(url); + } + +} diff --git a/catalog-ui/src/app/ng2/services/archive.service.ts b/catalog-ui/src/app/ng2/services/archive.service.ts deleted file mode 100644 index 83f1c502c2..0000000000 --- a/catalog-ui/src/app/ng2/services/archive.service.ts +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -import { Injectable, Inject } from "@angular/core"; -import { Observable } from "rxjs/Observable"; -import { HttpService } from "./http.service"; -import { SdcConfigToken, ISdcConfig } from "../config/sdc-config.config"; -import { Component } from "../../models"; -import { ComponentFactory } from 'app/utils/component-factory'; - - -@Injectable() -export class ArchiveService { - protected baseUrl; - - constructor(private http: HttpService, @Inject(SdcConfigToken) sdcConfig:ISdcConfig, private componentFactory:ComponentFactory/*, @Inject(ComponentFactory) componentFactory */) { - this.baseUrl = sdcConfig.api.root ; - } - - public getArchiveCatalog() { - let archiveCatalogItems:Component[] = []; - let archiveCatalogResourceItems:Component[] = []; - let archiveCatalogServiceItems:Component[] = []; - - return this.http.get(this.baseUrl + '/v1/catalog/archive/', {}).map(res => { - let archiveCatalogObject = res.json(); - if (archiveCatalogObject.resources) archiveCatalogResourceItems = this.getResourceItems(archiveCatalogObject.resources); - if (archiveCatalogObject.services) archiveCatalogServiceItems = this.getServiceItems(archiveCatalogObject.services); - archiveCatalogItems = [].concat(archiveCatalogResourceItems, archiveCatalogServiceItems); - - return archiveCatalogItems; - }); - } - - - private getResourceItems(resources){ - let resourceItems = resources.map((resource)=>{ - return this.componentFactory.createResource(resource) - }) - return resourceItems; - } - - private getServiceItems(services){ - let serviceItems = services.map((service)=>{ - return this.componentFactory.createService(service) - }) - return serviceItems; - } - -} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/services/authentication.service.ts b/catalog-ui/src/app/ng2/services/authentication.service.ts index 1c6502dd0d..52ca643833 100644 --- a/catalog-ui/src/app/ng2/services/authentication.service.ts +++ b/catalog-ui/src/app/ng2/services/authentication.service.ts @@ -20,38 +20,44 @@ import {Injectable, Inject} from '@angular/core'; import {IAppConfigurtaion, ICookie} from "../../models/app-config"; -import {Response, Headers, RequestOptions, Http} from '@angular/http'; import {Cookie2Service} from "./cookie.service"; import { Observable } from 'rxjs/Observable'; import {SdcConfigToken, ISdcConfig} from "../config/sdc-config.config"; +import { IUserProperties } from "app/models"; +import { CacheService } from "app/ng2/services/cache.service"; +import { HttpClient, HttpHeaders } from '@angular/common/http'; @Injectable() export class AuthenticationService { - constructor(private cookieService:Cookie2Service, private http: Http, @Inject(SdcConfigToken) private sdcConfig:ISdcConfig) { + private _loggedinUser:IUserProperties; + + constructor(private cookieService:Cookie2Service, private http: HttpClient, @Inject(SdcConfigToken) private sdcConfig:ISdcConfig, private cacheService: CacheService) { this.cookieService = cookieService; - this.http = http; } - private getAuthHeaders():any { + private getAuthHeaders():HttpHeaders { let cookie:ICookie = this.sdcConfig.cookie; - let authHeaders:any = {}; - authHeaders[cookie.userFirstName] = this.cookieService.getFirstName(); - authHeaders[cookie.userLastName] = this.cookieService.getLastName(); - authHeaders[cookie.userEmail] = this.cookieService.getEmail(); - authHeaders[cookie.userIdSuffix] = this.cookieService.getUserId(); + let authHeaders: HttpHeaders = new HttpHeaders(); + authHeaders = authHeaders.set(cookie.userFirstName, this.cookieService.getFirstName()) + .set(cookie.userLastName, this.cookieService.getLastName()) + .set(cookie.userEmail, this.cookieService.getEmail()) + .set(cookie.userIdSuffix, this.cookieService.getUserId()) return authHeaders; } - public authenticate(): Observable { - let options = new RequestOptions({ - headers: new Headers(this.getAuthHeaders()) - }); - + public authenticate(): Observable { let authUrl = this.sdcConfig.api.root + this.sdcConfig.api.GET_user_authorize; - return this.http - .get(authUrl, options) - .map((res: Response) => res.json()); + return this.http.get(authUrl, {headers: this.getAuthHeaders()}); + } + + public getLoggedinUser():IUserProperties { + return this._loggedinUser; } + public setLoggedinUser(loggedinUser:IUserProperties) { + this._loggedinUser = loggedinUser; + this.cacheService.set('user', loggedinUser); + }; + } diff --git a/catalog-ui/src/app/ng2/services/cache.service.ts b/catalog-ui/src/app/ng2/services/cache.service.ts new file mode 100644 index 0000000000..e876ec1098 --- /dev/null +++ b/catalog-ui/src/app/ng2/services/cache.service.ts @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +import {Injectable} from "@angular/core"; +import {Dictionary} from "app/utils"; + +@Injectable() +export class CacheService { + private storage:Dictionary; + + constructor() { + this.storage = new Dictionary(); + }; + + public get(key:string): any { + return this.storage.getValue(key); + } + + public set(key:string, value:any): void { + this.storage.setValue(key, value); + } + + public remove(key:string): void { + if (this.storage.containsKey(key)) { + this.storage.remove(key); + } + } + + public contains(key:string): boolean { + return this.storage.containsKey(key); + } +} diff --git a/catalog-ui/src/app/ng2/services/catalog.service.ts b/catalog-ui/src/app/ng2/services/catalog.service.ts new file mode 100644 index 0000000000..bbdfa1b420 --- /dev/null +++ b/catalog-ui/src/app/ng2/services/catalog.service.ts @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +import { Injectable, Inject } from "@angular/core"; +import { Observable } from "rxjs/Observable"; +import { SdcConfigToken, ISdcConfig } from "../config/sdc-config.config"; +import { Component, IApi, IComponentsArray } from "app/models"; +import { ComponentFactory } from 'app/utils/component-factory'; +import {ResourceType} from "../../utils/constants"; +import {SharingService} from "./sharing.service"; +import { HttpClient, HttpParams } from "@angular/common/http"; + +@Injectable() +export class CatalogService { + protected api:IApi; + protected baseUrl:string; + protected baseMicroServiceUrl:string; + + constructor(private http: HttpClient, + @Inject(SdcConfigToken) sdcConfig:ISdcConfig, + private componentFactory:ComponentFactory, + private sharingService:SharingService) { + this.api = sdcConfig.api; + this.baseUrl = sdcConfig.api.root ; + this.baseMicroServiceUrl = sdcConfig.api.uicache_root; + } + + public getCatalog(): Observable> { + let searchParams = new HttpParams(); + searchParams = searchParams.append('excludeTypes', ResourceType.VFCMT).append('excludeTypes', ResourceType.CONFIGURATION); + return this.http.get(this.baseMicroServiceUrl + this.api.GET_uicache_catalog, {params: searchParams}) + .map(res => this.processComponentsResponse(res, true)); + } + + public getArchiveCatalog() { + return this.http.get(this.baseUrl + '/v1/catalog/archive/', {}) + .map(res => this.processComponentsResponse(res)); + } + + private processComponentsResponse(componentsArr: IComponentsArray, addSharing:boolean = false) { + const componentsList: Component[] = []; + if (componentsArr.resources) { + componentsList.push(...this.getResourceItems(componentsArr.resources)); + } + if (componentsArr.services) { + componentsList.push(...this.getServiceItems(componentsArr.services)); + } + if (addSharing) { + componentsList.forEach((item) => this.sharingService.addUuidValue(item.uniqueId, item.uuid)); + } + return componentsList; + } + + private getResourceItems(resources){ + let resourceItems = resources.map((resource)=>{ + return this.componentFactory.createResource(resource) + }) + return resourceItems; + } + + private getServiceItems(services){ + let serviceItems = services.map((service)=>{ + return this.componentFactory.createService(service) + }) + return serviceItems; + } + +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/services/component-instance-services/component-instance.service.ts b/catalog-ui/src/app/ng2/services/component-instance-services/component-instance.service.ts index 15750020dc..cc382a3df0 100644 --- a/catalog-ui/src/app/ng2/services/component-instance-services/component-instance.service.ts +++ b/catalog-ui/src/app/ng2/services/component-instance-services/component-instance.service.ts @@ -19,62 +19,102 @@ */ import {Injectable, Inject} from '@angular/core'; -import {Response, RequestOptions, Headers} from '@angular/http'; import { Observable } from 'rxjs/Observable'; import {PropertyFEModel, PropertyBEModel} from "app/models"; -import {CommonUtils} from "app/utils"; -import {Component, ComponentInstance, Capability, PropertyModel} from "app/models"; -import { HttpService } from '../http.service'; +import {CommonUtils, ComponentType, ServerTypeUrl, ComponentInstanceFactory} from "app/utils"; +import {Component, ComponentInstance, Capability, PropertyModel, ArtifactGroupModel, ArtifactModel, AttributeModel, IFileDownload} from "app/models"; import {SdcConfigToken, ISdcConfig} from "../../config/sdc-config.config"; +import { HttpClient, HttpHeaders } from '@angular/common/http'; +import { InputBEModel } from '../../../models/properties-inputs/input-be-model'; +import { HttpHelperService } from '../http-hepler.service'; @Injectable() export class ComponentInstanceServiceNg2 { protected baseUrl; - constructor(private http: HttpService, @Inject(SdcConfigToken) sdcConfig:ISdcConfig) { + constructor(private http: HttpClient, @Inject(SdcConfigToken) sdcConfig:ISdcConfig) { this.baseUrl = sdcConfig.api.root + sdcConfig.api.component_api_root; } + private getServerTypeUrl = (componentType:string):string => { + switch (componentType) { + case ComponentType.SERVICE: + return ServerTypeUrl.SERVICES; + default: + return ServerTypeUrl.RESOURCES; + } + } getComponentInstanceProperties(component: Component, componentInstanceId: string): Observable> { - - return this.http.get(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/componentInstances/' + componentInstanceId + '/properties') - .map((res: Response) => { - return CommonUtils.initBeProperties(res.json()); + return this.http.get>(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/componentInstances/' + componentInstanceId + '/properties') + .map(res => { + return CommonUtils.initBeProperties(res); }) } getComponentInstanceInputs(component: Component, componentInstance: ComponentInstance): Observable> { - return this.http.get(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/componentInstances/' + componentInstance.uniqueId + '/' + componentInstance.componentUid + '/inputs') - .map((res: Response) => { - return CommonUtils.initInputs(res.json()); + return this.http.get>(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/componentInstances/' + componentInstance.uniqueId + '/' + componentInstance.componentUid + '/inputs') + .map(res => { + return CommonUtils.initInputs(res); }) } - updateInstanceProperties(component: Component, componentInstanceId: string, properties: PropertyBEModel[]) { + getComponentInstanceArtifactsByGroupType = (componentType:string, componentId:string, componentInstanceId:string, artifactGroupType:string):Observable => { + + return this.http.get(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + "/resourceInstances/" + componentInstanceId + "/artifactsByType/" + artifactGroupType) + .map(res => { + return new ArtifactGroupModel(res); + }); + }; + + getArtifactByGroupType = (componentType:string, componentId:string, artifactGroupType:string):Observable => { + + return this.http.get(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + "/artifactsByType/" + artifactGroupType) + .map(response => new ArtifactGroupModel(response)); + }; + + changeResourceInstanceVersion = (componentType:string, componentId:string, componentInstanceId:string, componentUid:string):Observable => { + return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/resourceInstance/' + componentInstanceId + '/changeVersion', {'componentUid': componentUid}) + .map((res) => { + return ComponentInstanceFactory.createComponentInstance(res); + }) + }; - return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/resourceInstance/' + componentInstanceId + '/properties', properties) - .map((res: Response) => { - return res.json().map((resProperty) => new PropertyBEModel(resProperty)); + updateComponentInstance = (componentType:string, componentId:string, componentInstance:ComponentInstance):Observable => { + return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/resourceInstance/' + componentInstance.uniqueId, componentInstance.toJSON()) + .map((response) => { + return ComponentInstanceFactory.createComponentInstance(response); + }); + }; + + updateInstanceProperties(componentType:string, componentId:string, componentInstanceId: string, properties: PropertyBEModel[]) { + + return this.http.post>(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/resourceInstance/' + componentInstanceId + '/properties', properties) + .map((res) => { + return res.map((resProperty) => { + let newProp = new PropertyModel(resProperty); + newProp.resourceInstanceUniqueId = componentInstanceId + return newProp; + }); }); } - getInstanceCapabilityProperties(component: Component, componentInstanceId: string, capability: Capability): Observable> { + getInstanceCapabilityProperties(componentType: string, componentId: string, componentInstanceId: string, capability: Capability): Observable> { - return this.http.get(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/componentInstances/' + componentInstanceId + '/capability/' + capability.type + + return this.http.get>(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/componentInstances/' + componentInstanceId + '/capability/' + capability.type + '/capabilityName/' + capability.name + '/ownerId/' + capability.ownerId + '/properties') - .map((res: Response) => { - capability.properties = res.json().map((capProp) => new PropertyModel(capProp)); // update capability properties + .map((res) => { + capability.properties = res.map((capProp) => new PropertyModel(capProp)); // update capability properties return capability.properties; }) } updateInstanceCapabilityProperties(component: Component, componentInstanceId: string, capability: Capability, properties: PropertyBEModel[]): Observable> { - return this.http.put(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/componentInstances/' + componentInstanceId + '/capability/' + capability.type + + return this.http.put>(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/componentInstances/' + componentInstanceId + '/capability/' + capability.type + '/capabilityName/' + capability.name + '/ownerId/' + capability.ownerId + '/properties', properties) - .map((res: Response) => { - const savedProperties: PropertyModel[] = res.json().map((resProperty) => new PropertyModel(resProperty)); + .map((res) => { + const savedProperties: PropertyModel[] = res.map((resProperty) => new PropertyModel(resProperty)); savedProperties.forEach((savedProperty) => { const propIdx = capability.properties.findIndex((p) => p.uniqueId === savedProperty.uniqueId); if (propIdx !== -1) { @@ -87,37 +127,87 @@ export class ComponentInstanceServiceNg2 { updateInstanceInputs(component: Component, componentInstanceId: string, inputs: PropertyBEModel[]): Observable { - return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/resourceInstance/' + componentInstanceId + '/inputs', inputs) - .map((res: Response) => { - return res.json().map((resInput) => new PropertyBEModel(resInput)); + return this.http.post>(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/resourceInstance/' + componentInstanceId + '/inputs', inputs) + .map((res) => { + return res.map((resInput) => new PropertyBEModel(resInput)); }); } getComponentGroupInstanceProperties(component: Component, groupInstanceId: string): Observable> { - return this.http.get(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/groups/' + groupInstanceId + '/properties') - .map((res: Response) => { - return CommonUtils.initBeProperties(res.json()); + return this.http.get>(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/groups/' + groupInstanceId + '/properties') + .map((res) => { + return CommonUtils.initBeProperties(res); + }); + } + + updateComponentGroupInstanceProperties(componentType:string, componentId:string, groupInstanceId: string, properties: PropertyBEModel[]): Observable> { + return this.http.put>(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/groups/' + groupInstanceId + '/properties', properties) + .map((res) => { + return res.map((resProperty) => new PropertyBEModel(resProperty)); }); } - updateComponentGroupInstanceProperties(component: Component, groupInstanceId: string, properties: PropertyBEModel[]): Observable> { - return this.http.put(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/groups/' + groupInstanceId + '/properties', properties) - .map((res: Response) => { - return res.json().map((resProperty) => new PropertyBEModel(resProperty)); + getComponentPolicyInstanceProperties(componentType:string, componentId:string, policyInstanceId: string): Observable> { + return this.http.get>(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/policies/' + policyInstanceId + '/properties') + .map((res) => { + return CommonUtils.initBeProperties(res); }); } - getComponentPolicyInstanceProperties(component: Component, policyInstanceId: string): Observable> { - return this.http.get(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/policies/' + policyInstanceId + '/properties') - .map((res: Response) => { - return CommonUtils.initBeProperties(res.json()); + updateComponentPolicyInstanceProperties(componentType:string, componentId:string, policyInstanceId: string, properties: PropertyBEModel[]): Observable> { + return this.http.put>(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/policies/' + policyInstanceId + '/properties', properties) + .map((res) => { + return res.map((resProperty) => new PropertyBEModel(resProperty)); }); } - updateComponentPolicyInstanceProperties(component: Component, policyInstanceId: string, properties: PropertyBEModel[]): Observable> { - return this.http.put(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/policies/' + policyInstanceId + '/properties', properties) - .map((res: Response) => { - return res.json().map((resProperty) => new PropertyBEModel(resProperty)); + addInstanceArtifact = (componentType:string, componentId:string, instanceId:string, artifact:ArtifactModel):Observable => { + // let deferred = this.$q.defer(); + let headerObj = new HttpHeaders(); + if (artifact.payloadData) { + headerObj = headerObj.set('Content-MD5', HttpHelperService.getHeaderMd5(artifact)); + } + return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/resourceInstance/' + instanceId + '/artifacts', JSON.stringify(artifact), {headers: headerObj}) + .map((res) => { + return new ArtifactModel(res); + }); + }; + + updateInstanceArtifact = (componentType:string, componentId:string, instanceId:string, artifact:ArtifactModel):Observable => { + return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/resourceInstance/' + instanceId + '/artifacts/' + artifact.uniqueId, artifact).map((res) => { + return new ArtifactModel(res); + });; + }; + + deleteInstanceArtifact = (componentId:string, componentType:string, instanceId:string, artifactId:string, artifactLabel:string):Observable => { + return this.http.delete(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + "/resourceInstance/" + instanceId + '/artifacts/' + artifactId + '?operation=' + artifactLabel) + .map((res) => { + return new ArtifactModel(res); }); } + + downloadInstanceArtifact = (componentType:string, componentId:string, instanceId:string, artifactId:string):Observable => { + return this.http.get(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + "/resourceInstances/" + instanceId + "/artifacts/" + artifactId); + }; + + uploadInstanceEnvFile = (componentType:string, componentId:string, instanceId:string, artifact:ArtifactModel):Observable => { + let headerObj = new HttpHeaders(); + if (artifact.payloadData) { + headerObj = headerObj.set('Content-MD5', HttpHelperService.getHeaderMd5(artifact)); + } + return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/resourceInstance/' + instanceId + '/artifacts/' + artifact.uniqueId, JSON.stringify(artifact), {headers: headerObj}); + }; + + + updateInstanceAttribute = (componentType:string, componentId:string, attribute:AttributeModel):Observable => { + let instanceId = attribute.resourceInstanceUniqueId; + return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + "/resourceInstance/" + instanceId + "/attribute", attribute) + .map((response) => { + let newAttribute = new AttributeModel(response); + newAttribute.readonly = true; + newAttribute.resourceInstanceUniqueId = instanceId; + return newAttribute; + }); + }; + } diff --git a/catalog-ui/src/app/ng2/services/component-services/component-mode.service.ts b/catalog-ui/src/app/ng2/services/component-services/component-mode.service.ts index b0cc1b8f1a..9952b03c7c 100644 --- a/catalog-ui/src/app/ng2/services/component-services/component-mode.service.ts +++ b/catalog-ui/src/app/ng2/services/component-services/component-mode.service.ts @@ -24,7 +24,7 @@ import { Injectable } from '@angular/core'; import {WorkspaceMode, ComponentState, Role} from "../../../utils/constants"; import { Component as ComponentData } from "app/models"; -import { CacheService } from "app/services/cache-service" +import { CacheService } from "app/services-ng2"; @Injectable() diff --git a/catalog-ui/src/app/ng2/services/component-services/component.service.factory.ts b/catalog-ui/src/app/ng2/services/component-services/component.service.factory.ts index 6e9d0e8031..15e5a7960a 100644 --- a/catalog-ui/src/app/ng2/services/component-services/component.service.factory.ts +++ b/catalog-ui/src/app/ng2/services/component-services/component.service.factory.ts @@ -20,15 +20,18 @@ import {Injectable} from "@angular/core"; -import {Component} from "../../../models/components/component"; +import {Component} from "app/models"; import {ComponentServiceNg2} from "./component.service"; import {ServiceServiceNg2} from "./service.service"; +import {CacheService} from "app/services-ng2"; @Injectable() export class ComponentServiceFactoryNg2 { + componentService: ComponentServiceNg2; serviceService: ServiceServiceNg2; - constructor(componentService: ComponentServiceNg2, serviceService: ServiceServiceNg2) { + + constructor(componentService: ComponentServiceNg2, serviceService: ServiceServiceNg2, private cacheService:CacheService) { this.serviceService = serviceService; this.componentService = componentService; } diff --git a/catalog-ui/src/app/ng2/services/component-services/component.service.ts b/catalog-ui/src/app/ng2/services/component-services/component.service.ts index 445e1231f9..760bfc591b 100644 --- a/catalog-ui/src/app/ng2/services/component-services/component.service.ts +++ b/catalog-ui/src/app/ng2/services/component-services/component.service.ts @@ -23,51 +23,52 @@ import {Injectable, Inject} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/toPromise'; -import {Response, URLSearchParams, Headers} from '@angular/http'; -import { Component, ComponentInstance, InputBEModel, InstancePropertiesAPIMap, FilterPropertiesAssignmentData, - PropertyBEModel, InterfaceModel, OperationModel, BEOperationModel, Capability, Requirement, PolicyInstance} from "app/models"; -import {COMPONENT_FIELDS, CommonUtils, SERVICE_FIELDS} from "app/utils"; -import {downgradeInjectable} from '@angular/upgrade/static'; +import { Component, InputBEModel, InstancePropertiesAPIMap, FilterPropertiesAssignmentData, OperationModel, CreateOperationResponse, ArtifactModel} from "app/models"; +import {COMPONENT_FIELDS} from "app/utils"; import {ComponentGenericResponse} from "../responses/component-generic-response"; import {InstanceBePropertiesMap} from "../../../models/properties-inputs/property-fe-map"; import {API_QUERY_PARAMS} from "app/utils"; -import { ComponentType, ServerTypeUrl } from "../../../utils/constants"; -import { HttpService } from '../http.service'; +import {ComponentType, ServerTypeUrl, SERVICE_FIELDS} from "../../../utils/constants"; import {SdcConfigToken, ISdcConfig} from "../../config/sdc-config.config"; -import {ConstraintObject} from 'app/ng2/components/logic/service-dependencies/service-dependencies.component'; import {IDependenciesServerResponse} from "../responses/dependencies-server-response"; import {AutomatedUpgradeGenericResponse} from "../responses/automated-upgrade-response"; import {IAutomatedUpgradeRequestObj} from "../../pages/automated-upgrade/automated-upgrade.service"; - -declare var angular:angular.IAngularStatic; - +import {ComponentInstance} from "../../../models/componentsInstances/componentInstance"; +import {CommonUtils} from "../../../utils/common-utils"; +import {RelationshipModel} from "../../../models/graph/relationship"; +import { HttpClient, HttpParams, HttpHeaders } from "@angular/common/http"; +import { BEOperationModel, InterfaceModel } from "../../../models/operation"; +import { PropertyBEModel } from "../../../models/properties-inputs/property-be-model"; +import { PolicyInstance } from "../../../models/graph/zones/policy-instance"; +import { ConstraintObject } from "../../components/logic/service-dependencies/service-dependencies.component"; +import { Requirement } from "../../../models/requirement"; +import { Capability } from "../../../models/capability"; + +/* +PLEASE DO NOT USE THIS SERVICE IN ANGULAR2! Use the topology-template.service instead + */ @Injectable() export class ComponentServiceNg2 { protected baseUrl; - constructor(protected http:HttpService, @Inject(SdcConfigToken) sdcConfig:ISdcConfig) { + constructor(protected http: HttpClient, @Inject(SdcConfigToken) sdcConfig:ISdcConfig) { this.baseUrl = sdcConfig.api.root + sdcConfig.api.component_api_root; } - protected getComponentDataByFieldsName(componentType:string, componentId: string, fields:Array):Observable { + protected getComponentDataByFieldsName(componentType:string, componentId:string, fields:Array):Observable { - let params:URLSearchParams = new URLSearchParams(); + let params: HttpParams = new HttpParams(); _.forEach(fields, (field:string):void => { - params.append(API_QUERY_PARAMS.INCLUDE, field); + params = params.append(API_QUERY_PARAMS.INCLUDE, field); }); - return this.http.get(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/filteredDataByParams', {search: params}) - .map((res:Response) => { - return this.analyzeComponentDataResponse(res); + return this.http.get(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/filteredDataByParams', {params: params}) + .map((res) => { + return new ComponentGenericResponse().deserialize(res); }); } - - protected analyzeComponentDataResponse(res: Response):ComponentGenericResponse { - return new ComponentGenericResponse().deserialize(res.json()); - } - - private getServerTypeUrl = (componentType:string):string => { + protected getServerTypeUrl = (componentType:string):string => { switch (componentType) { case ComponentType.SERVICE: return ServerTypeUrl.SERVICES; @@ -76,15 +77,23 @@ export class ComponentServiceNg2 { } } - getComponentMetadata(component:Component):Observable { - return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_METADATA]); + getFullComponent(uniqueId:string):Observable { + return this.http.get(this.baseUrl + uniqueId) + .map((res) => { + return new ComponentGenericResponse().deserialize(res); + }); } + getComponentMetadata(uniqueId:string, type:string):Observable { + return this.getComponentDataByFieldsName(type, uniqueId, [COMPONENT_FIELDS.COMPONENT_METADATA]); + } + + getComponentInstanceAttributesAndProperties(component:Component):Observable { return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INSTANCES_PROPERTIES, COMPONENT_FIELDS.COMPONENT_INSTANCES_ATTRIBUTES]); } - getComponentInstanceProperties(component:Component):Observable { + getComponentInstanceProperties(component:Component): Observable { return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INSTANCES_PROPERTIES]); } @@ -132,17 +141,15 @@ export class ComponentServiceNg2 { return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_PROPERTIES]); } - getInterfaces(component:Component):Observable { + getInterfaceOperations(component:Component):Observable { return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INTERFACE_OPERATIONS]); } getInterfaceOperation(component:Component, operation:OperationModel):Observable { - return this.http.get(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/interfaces/' + operation.interfaceId + '/operations/' + operation.uniqueId) - .map((res:Response) => { - return res.json(); - }); + return this.http.get(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/interfaceOperations/' + operation.uniqueId); } + // tslint:disable-next-line:member-ordering createInterfaceOperation(component:Component, operation:OperationModel):Observable { const operationList = { 'interfaces': { @@ -154,9 +161,9 @@ export class ComponentServiceNg2 { } } }; - return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/interfaceOperations', operationList) - .map((res:Response) => { - const interf:InterfaceModel = _.find(res.json().interfaces, interf => interf.type === operation.interfaceType); + return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/interfaceOperations', operationList) + .map((res:any) => { + const interf:InterfaceModel = _.find(res.interfaces, interf => interf.type === operation.interfaceType); const newOperation:OperationModel = _.find(interf.operations, op => op.name === operation.name); return new OperationModel({ ...newOperation, @@ -167,21 +174,22 @@ export class ComponentServiceNg2 { }); } + // tslint:disable-next-line:member-ordering updateInterfaceOperation(component:Component, operation:OperationModel):Observable { const operationList = { - 'interfaces': { + interfaces: { [operation.interfaceType]: { - 'type': operation.interfaceType, - 'operations': { + type: operation.interfaceType, + operations: { [operation.name]: new BEOperationModel(operation) } } } }; - return this.http.put(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/interfaceOperations', operationList) - .map((res:Response) => { - const interf:InterfaceModel = _.find(res.json().interfaces, interf => interf.type === operation.interfaceType); - const newOperation:OperationModel = _.find(interf.operations, op => op.name === operation.name); + return this.http.put(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/interfaceOperations', operationList) + .map((res: any) => { + const interf: InterfaceModel = _.find(res.interfaces, interf => interf.type === operation.interfaceType); + const newOperation: OperationModel = _.find(interf.operations, op => op.name === operation.name); return new OperationModel({ ...newOperation, interfaceType: interf.type, @@ -191,18 +199,16 @@ export class ComponentServiceNg2 { }); } - deleteInterfaceOperation(component:Component, operation:OperationModel):Observable { - return this.http.delete(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/interfaces/' + operation.interfaceId + '/operations/' + operation.uniqueId) - .map((res:Response) => { - return res.json(); - }); + + deleteInterfaceOperation(component: Component, operation:OperationModel):Observable { + return this.http.delete(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/interfaces/' + operation.interfaceId + '/operations/' + operation.uniqueId); } getInterfaceTypes(component:Component):Observable<{[id:string]: Array}> { - return this.http.get(this.baseUrl + 'interfaceLifecycleTypes') - .map((res:Response) => { + return this.http.get(this.baseUrl + 'interfaceLifecycleTypes') + .map((res: any) => { const interfaceMap = {}; - _.forEach(res.json(), (interf:any) => { + _.forEach(res, (interf: any) => { interfaceMap[interf.toscaPresentation.type] = _.keys(interf.toscaPresentation.operations); }); return interfaceMap; @@ -217,19 +223,18 @@ export class ComponentServiceNg2 { payloadData: oldOperation.artifactData }; - const headers = new Headers(); + const headers = new HttpHeaders(); JSON.stringify(payload); const payloadString = JSON.stringify(payload, null, ' '); const md5Result = md5(payloadString).toLowerCase(); headers.append('Content-MD5', btoa(md5Result)); return this.http.post(this.baseUrl + component.getTypeUrl() + component.uuid + '/interfaces/' + newOperation.interfaceId + '/operations/' + newOperation.uniqueId + '/artifacts/' + newOperation.implementation.artifactUUID, - payload, - {headers} - ).map((res: Response) => { - const fileName = res.json().artifactDisplayName || res.json().artifactName; + payload, {headers} + ).map((res: any) => { + const fileName = res.artifactDisplayName || res.artifactName; newOperation.artifactFileName = fileName; - return res.json(); + return res; }); } @@ -237,78 +242,17 @@ export class ComponentServiceNg2 { return this.getComponentDataByFieldsName(componentType, componentId, [COMPONENT_FIELDS.COMPONENT_REQUIREMENTS, COMPONENT_FIELDS.COMPONENT_CAPABILITIES]); } - createCapability(component: Component, capabilityData: Capability): Observable> { - let capBEObj = { - 'capabilities': { - [capabilityData.type]: [capabilityData] - } - }; - return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/capabilities', capBEObj) - .map((res: Response) => { - return res.json(); - }); - } - updateCapability(component: Component, capabilityData: Capability): Observable> { - let capBEObj = { - 'capabilities': { - [capabilityData.type]: [capabilityData] - } - }; - return this.http.put(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/capabilities', capBEObj) - .map((res: Response) => { - return res.json(); - }); - } - deleteCapability(component: Component, capId: string): Observable { - return this.http.delete(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/capabilities/' + capId) - .map((res: Response) => { - return res.json(); - }); - } - createRequirement(component: Component, requirementData: Requirement): Observable { - let reqBEObj = { - 'requirements': { - [requirementData.capability]: [requirementData] - } - }; - return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/requirements', reqBEObj) - .map((res: Response) => { - return res.json(); - }); - } - - updateRequirement(component: Component, requirementData: Requirement): Observable { - let reqBEObj = { - 'requirements': { - [requirementData.capability]: [requirementData] - } - }; - return this.http.put(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/requirements', reqBEObj) - .map((res: Response) => { - return res.json(); - }); - } - - deleteRequirement(component: Component, reqId: string): Observable { - return this.http.delete(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/requirements/' + reqId) - .map((res: Response) => { - return res.json(); - }); - } getDeploymentGraphData(component:Component):Observable { return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INSTANCES_RELATION, COMPONENT_FIELDS.COMPONENT_INSTANCES, COMPONENT_FIELDS.COMPONENT_GROUPS]); } createInput(component:Component, inputsToCreate:InstancePropertiesAPIMap, isSelf:boolean):Observable { - let inputs = isSelf ? { serviceProperties: inputsToCreate.componentInstanceProperties } : inputsToCreate; - return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/create/inputs', inputs) - .map(res => { - return res.json(); - }) + const inputs = isSelf ? { serviceProperties: inputsToCreate.componentInstanceProperties } : inputsToCreate; + return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/create/inputs', inputs); } createListInput(component:Component, input:any, isSelf:boolean):Observable { @@ -324,10 +268,7 @@ export class ComponentServiceNg2 { } else { inputs = input; } - return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/create/listInput', inputs) - .map(res => { - return res.json(); - }) + return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/create/listInput', inputs); } createPolicy(component:Component, policiesToCreate:InstancePropertiesAPIMap, isSelf:boolean):Observable { @@ -341,78 +282,71 @@ export class ComponentServiceNg2 { ...policiesToCreate.componentInstanceProperties } }; - return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/create/policies', policiesList) - .map(res => { - return res.json(); - }); + return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/create/policies', policiesList); } deletePolicy(component:Component, policy: PolicyInstance) { - return this.http.put(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/policies/' + policy.uniqueId + '/undeclare', policy) - .map(res => { - return res.json(); - }); + return this.http.put(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/policies/' + policy.uniqueId + '/undeclare', policy); } - restoreComponent(componentType:string, componentId:string){ + restoreComponent(componentType:string, componentId:string) { return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/restore', {}) } - archiveComponent(componentType:string, componentId:string){ + archiveComponent(componentType:string, componentId:string) { return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/archive', {}) } deleteInput(component:Component, input:InputBEModel):Observable { - return this.http.delete(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/delete/' + input.uniqueId + '/input') - .map((res:Response) => { - return new InputBEModel(res.json()); - }); + + return this.http.delete(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/delete/' + input.uniqueId + '/input') + .map((res) => { + return new InputBEModel(res); + }) } updateComponentInputs(component:Component, inputs:InputBEModel[]):Observable { - return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/update/inputs', inputs) - .map((res:Response) => { - return res.json().map((input) => new InputBEModel(input)); + + return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/update/inputs', inputs) + .map((res) => { + return res.map((input) => new InputBEModel(input)); }) } - filterComponentInstanceProperties(component: Component, filterData:FilterPropertiesAssignmentData): Observable {//instance-property-be-map - let params: URLSearchParams = new URLSearchParams(); + filterComponentInstanceProperties(component:Component, filterData:FilterPropertiesAssignmentData):Observable {//instance-property-be-map + let params: HttpParams = new HttpParams(); _.forEach(filterData.selectedTypes, (type:string) => { - params.append('resourceType', type); + params = params.append('resourceType', type); }); - return this.http.get(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/filteredproperties/' + filterData.propertyName, {search: params}) - .map((res: Response) => { - return res.json(); - }); + return this.http.get(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/filteredproperties/' + filterData.propertyName, {params: params}); } createServiceProperty(component: Component, propertyModel:PropertyBEModel): Observable { let serverObject = {}; serverObject[propertyModel.name] = propertyModel; return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/properties', serverObject) - .map(res => { - let property:PropertyBEModel = new PropertyBEModel(res.json()); + .map((res: PropertyBEModel) => { + const property: PropertyBEModel = new PropertyBEModel(res); return property; }) } - getServiceProperties(component: Component): Observable> { + getServiceProperties(component: Component): Observable { return this.http.get(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/properties') - .map((res: Response) => { - if (!res.text()){ + .map((res: PropertyBEModel[]) => { + if (!res) { return new Array(); } - return CommonUtils.initBeProperties(res.json()); + return CommonUtils.initBeProperties(res); }); } updateServiceProperties(component: Component, properties: PropertyBEModel[]) { - return this.http.put( this.baseUrl + component.getTypeUrl() + component.uniqueId + '/properties', properties) - .map((res: Response) => { - const resJson = res.json(); + return this.http.put( this.baseUrl + component.getTypeUrl() + component.uniqueId + '/properties', properties) + .map((res) => { + const resJson = res; return _.map(resJson, (resValue:PropertyBEModel) => new PropertyBEModel(resValue)); }); @@ -425,25 +359,16 @@ export class ComponentServiceNg2 { }) } - getDependencies(componentType:string, componentId: string):Observable> { - return this.http.get(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/dependencies') - .map((res:Response) => { - return res.json(); - }); + getDependencies(componentType:string, componentId: string):Observable { + return this.http.get(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/dependencies'); } - automatedUpgrade(componentType:string, componentId: string, componentsIdsToUpgrade:Array):Observable { - return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/automatedupgrade', componentsIdsToUpgrade) - .map((res:Response) => { - return res.json(); - }); + automatedUpgrade(componentType:string, componentId:string, componentsIdsToUpgrade:IAutomatedUpgradeRequestObj[]):Observable { + return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/automatedupgrade', componentsIdsToUpgrade); } - updateComponentInstance(component:Component, componentInstance:ComponentInstance):Observable { - return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/resourceInstance/' + componentInstance.uniqueId, componentInstance) - .map((res:Response) => { - return res.json(); - }); + updateMultipleComponentInstances(componentId:string, instances:ComponentInstance[]):Observable { + return this.http.post(this.baseUrl + componentId + '/resourceInstance/multipleComponentInstance', instances); } getServiceFilterConstraints(component:Component):Observable { @@ -451,24 +376,18 @@ export class ComponentServiceNg2 { } createServiceFilterConstraints(component:Component, componentInstance:ComponentInstance, constraint:ConstraintObject):Observable { - return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/resourceInstances/' + componentInstance.uniqueId + '/nodeFilter', constraint) - .map((res:Response) => { - return res.json(); - }); + return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/resourceInstances/' + componentInstance.uniqueId + '/nodeFilter', constraint); } - updateServiceFilterConstraints(component:Component, componentInstance:ComponentInstance, constraints:Array):Observable { - return this.http.put(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/resourceInstances/' + componentInstance.uniqueId + '/nodeFilter/', constraints) - .map((res:Response) => { - return res.json(); - }); + updateServiceFilterConstraints(component:Component, componentInstance:ComponentInstance, constraints:ConstraintObject[]):Observable { + return this.http.put(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/resourceInstances/' + componentInstance.uniqueId + '/nodeFilter/', constraints); } deleteServiceFilterConstraints(component:Component, componentInstance:ComponentInstance, constraintIndex:number) { - return this.http.delete(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/resourceInstances/' + componentInstance.uniqueId + '/nodeFilter/' + constraintIndex) - .map((res:Response) => { - return res.json(); - }); + return this.http.delete(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/resourceInstances/' + componentInstance.uniqueId + '/nodeFilter/' + constraintIndex); } -} + protected analyzeComponentDataResponse(res: Response):ComponentGenericResponse { + return new ComponentGenericResponse().deserialize(res); + } +} diff --git a/catalog-ui/src/app/ng2/services/component-services/resource.service.ts b/catalog-ui/src/app/ng2/services/component-services/resource.service.ts index 699e762a60..d20f5415bc 100644 --- a/catalog-ui/src/app/ng2/services/component-services/resource.service.ts +++ b/catalog-ui/src/app/ng2/services/component-services/resource.service.ts @@ -21,14 +21,14 @@ import { Injectable } from '@angular/core'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/toPromise'; -import { Http, Response, Headers, RequestOptions } from '@angular/http'; +import { HttpClient } from '@angular/common/http'; @Injectable() export class ResourceServiceNg2 { protected baseUrl = ""; - constructor(private http: Http) { + constructor(private http: HttpClient) { } diff --git a/catalog-ui/src/app/ng2/services/component-services/service.service.ts b/catalog-ui/src/app/ng2/services/component-services/service.service.ts index dce4e814ec..9460a32323 100644 --- a/catalog-ui/src/app/ng2/services/component-services/service.service.ts +++ b/catalog-ui/src/app/ng2/services/component-services/service.service.ts @@ -22,9 +22,7 @@ import { Injectable, Inject } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/toPromise'; -import { Response, URLSearchParams } from '@angular/http'; -import {Service, OperationModel} from "app/models"; -import { HttpService } from '../http.service'; +import {Service} from "app/models"; import {SdcConfigToken, ISdcConfig} from "../../config/sdc-config.config"; import {ForwardingPath} from "app/models/forwarding-path"; @@ -34,77 +32,53 @@ import {Component} from "app/models/components/component"; import {ComponentGenericResponse} from "app/ng2/services/responses/component-generic-response"; import {COMPONENT_FIELDS, SERVICE_FIELDS} from "app/utils/constants"; import {ComponentServiceNg2} from "./component.service"; -import {ServiceGenericResponse} from "app/ng2/services/responses/service-generic-response"; import {ServicePathMapItem} from "app/models/graph/nodes-and-links-map"; -import {ConsumptionInput} from 'app/ng2/components/logic/service-consumption/service-consumption.component'; - +import { HttpClient, HttpParams } from '@angular/common/http'; +import { OperationModel } from '../../../models/operation'; +import { ConsumptionInput } from '../../components/logic/service-consumption/service-consumption.component'; @Injectable() export class ServiceServiceNg2 extends ComponentServiceNg2 { protected baseUrl = ""; - constructor(protected http: HttpService, @Inject(SdcConfigToken) sdcConfig:ISdcConfig) { + constructor(protected http: HttpClient, @Inject(SdcConfigToken) sdcConfig:ISdcConfig) { super(http, sdcConfig); this.baseUrl = sdcConfig.api.root + sdcConfig.api.component_api_root; } validateConformanceLevel(service: Service): Observable { - return this.http.get(this.baseUrl + service.getTypeUrl() + service.uuid + '/conformanceLevelValidation') - .map((res: Response) => { - return res.json(); - }); - } - - getNodesAndLinksMap(service: Service):Observable> { - return this.http.get(this.baseUrl + service.getTypeUrl() + service.uniqueId + '/linksMap').map(res => { - return >res.json(); - }); - } - - getServicePath(service: Service, id: string):Observable { - return this.http.get(this.baseUrl + service.getTypeUrl() + service.uniqueId + '/paths/' + id) - .map(res => { - return res.json(); - }) + return this.http.get(this.baseUrl + service.getTypeUrl() + service.uuid + '/conformanceLevelValidation'); } - getServicePaths(service: Service):Observable { - return this.http.get(this.baseUrl + service.getTypeUrl() + service.uniqueId + '/paths') - .map(res => { - return res.json(); - }) + getNodesAndLinksMap(serviceId: string):Observable> { + return this.http.get>(this.baseUrl + 'services/' + serviceId + '/linksMap'); } - createOrUpdateServicePath(service: Service, inputsToCreate: ForwardingPath):Observable { + createOrUpdateServicePath(serviceId: string, inputsToCreate: ForwardingPath):Observable { if (inputsToCreate.uniqueId) { - return this.updateServicePath(service, inputsToCreate); + return this.updateServicePath(serviceId, inputsToCreate); } else { - return this.createServicePath(service, inputsToCreate); + return this.createServicePath(serviceId, inputsToCreate); } } - createServicePath(service: Service, inputsToCreate: ForwardingPath):Observable { + createServicePath(serviceId: string, inputsToCreate: ForwardingPath):Observable { let input = new ServicePathRequestData(inputsToCreate); - - return this.http.post(this.baseUrl + service.getTypeUrl() + service.uniqueId + '/paths', input) - .map(res => { - return this.parseServicePathResponse(res); - }); + return this.http.post(this.baseUrl + 'services/' + serviceId + '/paths', input).map((res:any) => { + return this.parseServicePathResponse(res); + }); } - deleteServicePath(service: Service, id: string):Observable { - return this.http.delete(this.baseUrl + service.getTypeUrl() + service.uniqueId + '/paths/' + id ) - .map((res) => { - return res.json(); - }); + deleteServicePath(serviceId: string, id: string):Observable { + return this.http.delete(this.baseUrl + 'services/' + serviceId + '/paths/' + id); } - updateServicePath(service: Service, inputsToUpdate:ForwardingPath):Observable { + updateServicePath(serviceId: string, inputsToUpdate:ForwardingPath):Observable { let input = new ServicePathRequestData(inputsToUpdate); - return this.http.put(this.baseUrl + service.getTypeUrl() + service.uniqueId + '/paths', input) + return this.http.put<{[key:string]:ForwardingPath}>(this.baseUrl + 'services/' + serviceId + '/paths', input) .map((res) => { return this.parseServicePathResponse(res); }); @@ -122,28 +96,25 @@ export class ServiceServiceNg2 extends ComponentServiceNg2 { } getServiceConsumptionInputs(service: Service, serviceInstanceId: String, interfaceId: string, operation: OperationModel): Observable { - return this.http.get(this.baseUrl + service.getTypeUrl() + service.uniqueId + '/consumption/' + serviceInstanceId + '/interfaces/' + interfaceId + '/operations/' + operation.uniqueId + '/inputs') - .map(res => { - return res.json(); - }); + return this.http.get(this.baseUrl + service.getTypeUrl() + service.uniqueId + '/consumption/' + serviceInstanceId + '/interfaces/' + interfaceId + + '/operations/' + operation.uniqueId + '/inputs'); } createOrUpdateServiceConsumptionInputs(service: Service, serviceInstanceId: String, consumptionInputsList: Array<{[id: string]: Array}>): Observable { return this.http.post(this.baseUrl + service.getTypeUrl() + service.uniqueId + '/consumption/' + serviceInstanceId, consumptionInputsList); } - checkComponentInstanceVersionChange(service: Service, newVersionId: string):Observable> { - let instanceId = service.selectedInstance.uniqueId; - let queries = {componentInstanceId: instanceId, newComponentInstanceId: newVersionId}; + checkComponentInstanceVersionChange(componentType:string, componentId:string, instanceId:string, newInstanceId:string):Observable> { + let queries = {componentInstanceId: instanceId, newComponentInstanceId: newInstanceId}; - let params:URLSearchParams = new URLSearchParams(); + let params:HttpParams = new HttpParams(); _.map(_.keys(queries), (key:string):void => { - params.append(key, queries[key]); + params = params.append(key, queries[key]); }); - let url = this.baseUrl + service.getTypeUrl() + service.uniqueId + '/paths-to-delete'; - return this.http.get(url, {search: params}).map((res: Response) => { - return res.json().forwardingPathToDelete; + let url = this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/paths-to-delete'; + return this.http.get(url, {params: params}).map((res) => { + return res.forwardingPathToDelete; }); } @@ -151,12 +122,8 @@ export class ServiceServiceNg2 extends ComponentServiceNg2 { return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INSTANCES_RELATION, COMPONENT_FIELDS.COMPONENT_INSTANCES, SERVICE_FIELDS.FORWARDING_PATHS, COMPONENT_FIELDS.COMPONENT_NON_EXCLUDED_POLICIES, COMPONENT_FIELDS.COMPONENT_NON_EXCLUDED_GROUPS]); } - protected analyzeComponentDataResponse(res: Response):ComponentGenericResponse { - return new ServiceGenericResponse().deserialize(res.json()); - } - - private parseServicePathResponse(res: Response):ForwardingPath { - let resJSON = res.json(); + private parseServicePathResponse(res: { [key:string]:ForwardingPath }):ForwardingPath { + let resJSON = res; let pathId = Object.keys(resJSON.forwardingPaths)[0]; let forwardingPath = resJSON.forwardingPaths[pathId]; let path:ForwardingPath = new ForwardingPath(); diff --git a/catalog-ui/src/app/ng2/services/component-services/topology-template.service.ts b/catalog-ui/src/app/ng2/services/component-services/topology-template.service.ts new file mode 100644 index 0000000000..0abb163404 --- /dev/null +++ b/catalog-ui/src/app/ng2/services/component-services/topology-template.service.ts @@ -0,0 +1,515 @@ +/** + * Created by ob0695 on 6/26/2018. + */ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +import * as _ from "lodash"; +import {Injectable, Inject} from '@angular/core'; +import {Observable} from 'rxjs/Observable'; +import 'rxjs/add/operator/map'; +import 'rxjs/add/operator/toPromise'; +import { + Component, + InputBEModel, + InstancePropertiesAPIMap, + FilterPropertiesAssignmentData, + ArtifactModel, + PropertyModel, + IFileDownload, + AttributeModel, + IAttributeModel, Capability, Requirement +} from "app/models"; +import {ArtifactGroupType, COMPONENT_FIELDS} from "app/utils"; +import {ComponentGenericResponse} from "../responses/component-generic-response"; +import {InstanceBePropertiesMap} from "../../../models/properties-inputs/property-fe-map"; +import {API_QUERY_PARAMS} from "app/utils"; +import {ComponentType, ServerTypeUrl, SERVICE_FIELDS} from "../../../utils/constants"; +import {SdcConfigToken, ISdcConfig} from "../../config/sdc-config.config"; +import {IDependenciesServerResponse} from "../responses/dependencies-server-response"; +import {AutomatedUpgradeGenericResponse} from "../responses/automated-upgrade-response"; +import {IAutomatedUpgradeRequestObj} from "../../pages/automated-upgrade/automated-upgrade.service"; +import {ComponentInstance} from "../../../models/componentsInstances/componentInstance"; +import {CommonUtils} from "../../../utils/common-utils"; +import {RelationshipModel} from "../../../models/graph/relationship"; +import {ServiceGenericResponse} from "../responses/service-generic-response"; +import { HttpClient, HttpParams, HttpHeaders } from "@angular/common/http"; +import { HttpHelperService } from "../http-hepler.service"; +import { + Component as TopologyTemplate, + FullComponentInstance, + Service, + OperationModel, +} from 'app/models'; +import { ConsumptionInput } from "../../components/logic/service-consumption/service-consumption.component"; +import { ConstraintObject } from "../../components/logic/service-dependencies/service-dependencies.component"; +import { ComponentMetadata } from "../../../models/component-metadata"; +import { PolicyInstance } from "../../../models/graph/zones/policy-instance"; +import { PropertyBEModel } from "../../../models/properties-inputs/property-be-model"; + +/* we need to use this service from now, we will remove component.service when we finish remove the angular1. + The service is duplicated since we can not use downgrades service with NGXS*/ + +@Injectable() +export class TopologyTemplateService { + + protected baseUrl; + + constructor(protected http: HttpClient, @Inject(SdcConfigToken) sdcConfig: ISdcConfig) { + this.baseUrl = sdcConfig.api.root + sdcConfig.api.component_api_root; + } + + getFullComponent(componentType: string, uniqueId: string): Observable { + return this.http.get(this.baseUrl + this.getServerTypeUrl(componentType) + uniqueId); + } + + getComponentMetadata(uniqueId: string, type: string): Observable { + return this.getComponentDataByFieldsName(type, uniqueId, [COMPONENT_FIELDS.COMPONENT_METADATA]); + } + + getComponentInstanceAttributesAndProperties(uniqueId: string, type: string): Observable { + return this.getComponentDataByFieldsName(type, uniqueId, [COMPONENT_FIELDS.COMPONENT_INSTANCES_PROPERTIES, COMPONENT_FIELDS.COMPONENT_INSTANCES_ATTRIBUTES]); + } + + async getComponentAttributes(componentType: string, componentId: string): Promise { + return this.getComponentDataByFieldsName(componentType, componentId, [COMPONENT_FIELDS.COMPONENT_ATTRIBUTES]).toPromise(); + } + + getComponentCompositionData(componentUniqueId: string, componentType: string): Observable { + const params: string[] = [COMPONENT_FIELDS.COMPONENT_INSTANCES_RELATION, COMPONENT_FIELDS.COMPONENT_INSTANCES, + COMPONENT_FIELDS.COMPONENT_NON_EXCLUDED_POLICIES, COMPONENT_FIELDS.COMPONENT_NON_EXCLUDED_GROUPS]; + if (componentType === ComponentType.SERVICE) { + params.push(COMPONENT_FIELDS.FORWARDING_PATHS); + } + return this.getComponentDataByFieldsName(componentType, componentUniqueId, params); + } + + getComponentResourcePropertiesData(component: Component): Observable { + return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, + [COMPONENT_FIELDS.COMPONENT_INSTANCES, COMPONENT_FIELDS.COMPONENT_POLICIES, COMPONENT_FIELDS.COMPONENT_NON_EXCLUDED_GROUPS]); + } + + getComponentResourceInstances(component: Component): Observable { + return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INSTANCES]); + } + + getComponentInputs(component: Component): Observable { + return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INPUTS]); + } + + getComponentInputsWithProperties(componentType: string, componentId: string): Observable { + return this.getComponentDataByFieldsName(componentType, componentId, + [COMPONENT_FIELDS.COMPONENT_INPUTS, COMPONENT_FIELDS.COMPONENT_INSTANCES, COMPONENT_FIELDS.COMPONENT_INSTANCES_PROPERTIES, COMPONENT_FIELDS.COMPONENT_PROPERTIES]); + } + + getComponentDeploymentArtifacts(component: Component): Observable { + return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_DEPLOYMENT_ARTIFACTS]); + } + + getComponentInformationalArtifacts(component: Component): Observable { + return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INFORMATIONAL_ARTIFACTS]); + } + + getComponentInformationalArtifactsAndInstances(component: Component): Observable { + return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INFORMATIONAL_ARTIFACTS, COMPONENT_FIELDS.COMPONENT_INSTANCES]); + } + + getComponentToscaArtifacts(componentType: string, componentId: string): Observable { + return this.getComponentDataByFieldsName(componentType, componentId, [COMPONENT_FIELDS.COMPONENT_TOSCA_ARTIFACTS]); + } + + getComponentProperties(component: Component): Observable { + return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_PROPERTIES]); + } + + getCapabilitiesAndRequirements(componentType: string, componentId: string): Observable { + return this.getComponentDataByFieldsName(componentType, componentId, [COMPONENT_FIELDS.COMPONENT_REQUIREMENTS, COMPONENT_FIELDS.COMPONENT_CAPABILITIES]); + } + + getRequirementsAndCapabilitiesWithProperties(componentType: string, componentId: string): Observable { + return this.getComponentDataByFieldsName(componentType, componentId, + [COMPONENT_FIELDS.COMPONENT_REQUIREMENTS, COMPONENT_FIELDS.COMPONENT_CAPABILITIES, COMPONENT_FIELDS.COMPONENT_CAPABILITIES_PROPERTIES]); + } + + getDeploymentGraphData(componentType: string, componentId: string): Observable { + return this.getComponentDataByFieldsName(componentType, componentId, [COMPONENT_FIELDS.COMPONENT_INSTANCES_RELATION, COMPONENT_FIELDS.COMPONENT_INSTANCES, COMPONENT_FIELDS.COMPONENT_GROUPS]); + } + + createInput(component: Component, inputsToCreate: InstancePropertiesAPIMap, isSelf: boolean): Observable { + const inputs = isSelf ? { serviceProperties: inputsToCreate.componentInstanceProperties } : inputsToCreate; + return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/create/inputs', inputs); + } + + restoreComponent(componentType: string, componentId: string) { + return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/restore', {}); + } + + archiveComponent(componentType: string, componentId: string) { + return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/archive', {}); + } + + deleteInput(component: Component, input: InputBEModel): Observable { + return this.http.delete(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/delete/' + input.uniqueId + '/input') + .map((res) => { + return new InputBEModel(res); + }); + } + + updateComponentInputs(component: Component, inputs: InputBEModel[]): Observable { + return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/update/inputs', inputs) + .map((res) => { + return res.map((input) => new InputBEModel(input)); + }); + } + + filterComponentInstanceProperties(component: Component, filterData: FilterPropertiesAssignmentData): Observable {// instance-property-be-map + let params: HttpParams = new HttpParams(); + _.forEach(filterData.selectedTypes, (type: string) => { + params = params.append('resourceType', type); + }); + + // tslint:disable-next-line:object-literal-shorthand + return this.http.get(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/filteredproperties/' + filterData.propertyName, {params: params}); + } + + createServiceProperty(componentId: string, propertyModel: PropertyBEModel): Observable { + const serverObject = {}; + serverObject[propertyModel.name] = propertyModel; + return this.http.post(this.baseUrl + 'services/' + componentId + '/properties', serverObject) + .map((res) => { + const property: PropertyBEModel = new PropertyBEModel(res); + return property; + }); + } + + getServiceProperties(componentId: string): Observable { + return this.http.get(this.baseUrl + 'services/' + componentId + '/properties') + .map((res) => { + if (!res) { + return new Array(); + } + return CommonUtils.initBeProperties(res); + }); + } + + updateServiceProperties(componentId: string, properties: PropertyBEModel[]) { + return this.http.put( this.baseUrl + 'services/' + componentId + '/properties', properties) + .map((res) => { + const resJson = res; + return _.map(resJson, + (resValue: PropertyBEModel) => new PropertyBEModel(resValue)); + }); + } + + deleteServiceProperty(componentId: string, property: PropertyBEModel): Observable { + return this.http.delete(this.baseUrl + 'services/' + componentId + '/properties/' + property.uniqueId ) + .map((res: Response) => { + return property.uniqueId; + }); + } + + getDependencies(componentType: string, componentId: string): Observable { + return this.http.get(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/dependencies'); + } + + automatedUpgrade(componentType: string, componentId: string, componentsIdsToUpgrade: IAutomatedUpgradeRequestObj[]): Observable { + return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/automatedupgrade', componentsIdsToUpgrade); + } + + updateComponentInstance(componentMetaDataId: string, componentInstance:ComponentInstance): Observable { + return this.http.post(this.baseUrl + 'services/' + componentMetaDataId + '/resourceInstance/' + componentInstance.uniqueId, componentInstance); + } + + updateMultipleComponentInstances(componentId: string, componentType: string, instances: ComponentInstance[]): Observable { + return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/resourceInstance/multipleComponentInstance', instances) + .map((res) => { + return CommonUtils.initComponentInstances(res); + }); + } + + createRelation(componentId: string, componentType: string, link: RelationshipModel): Observable { + return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/resourceInstance/associate', link) + .map((res) => { + return new RelationshipModel(res); + }); + } + + deleteRelation(componentId: string, componentType: string, link: RelationshipModel): Observable { + return this.http.put(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/resourceInstance/dissociate', link) + .map((res) => { + return new RelationshipModel(res); + }); + } + + createComponentInstance(componentType: string, componentId: string, componentInstance: ComponentInstance): Observable { + return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/resourceInstance', componentInstance) + .map((res) => { + return new ComponentInstance(res); + }); + } + + deleteComponentInstance(componentType: string, componentId: string, componentInstanceId: string): Observable { + return this.http.delete(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/resourceInstance/' + componentInstanceId) + .map((res) => { + return new ComponentInstance(res); + }); + } + + fetchRelation(componentType: string, componentId: string, linkId: string): Observable { + return this.http.get(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/relationId/' + linkId) + .map((res) => { + return new RelationshipModel(res); + }); + } + + addOrUpdateArtifact = (componentType: string, componentId: string, artifact: ArtifactModel): Observable => { + let headerObj: HttpHeaders = new HttpHeaders(); + if (artifact.payloadData) { + headerObj = headerObj.append('Content-MD5', HttpHelperService.getHeaderMd5(artifact)); + } + + let artifactID: string = ''; + if (artifact.uniqueId) { + artifactID = '/' + artifact.uniqueId; + } + return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/artifacts' + artifactID, JSON.stringify(artifact), {headers: headerObj}).map( + (res) => new ArtifactModel(res) + ); + } + + deleteArtifact = (componentId: string, componentType: string, artifactId: string, artifactLabel: string): Observable => { + return this.http.delete(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/artifacts/' + artifactId + '?operation=' + artifactLabel) + .map((res) => new ArtifactModel(res)); + } + + downloadArtifact = (componentType: string, componentId: string, artifactId: string): Observable => { + return this.http.get(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/artifacts/' + artifactId); + } + + // ------------------------------------------------ Properties API --------------------------------------------------// + addProperty = (componentType: string, componentId: string, property: PropertyModel):Observable => { + return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/properties', property.convertToServerObject()).map((response) => { + return new PropertyModel(response[Object.keys(response)[0]]); + }); + } + + updateProperty = (componentType: string, componentId: string, property: PropertyModel): Observable => { + var propertiesList:PropertyBEModel[] = [property]; + return this.http.put(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/properties', propertiesList) + .map((response) => { + return new PropertyModel(response[Object.keys(response)[0]]); + }); + } + + deleteProperty = (componentType: string, componentId: string, propertyId: string): Observable => { + return this.http.delete(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/properties/' + propertyId); + } + + // ------------------------------------------------ Attributes API --------------------------------------------------// + addAttribute = (componentType: string, componentId: string, attribute: AttributeModel): Observable => { + return this.http.post(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/attributes', attribute.convertToServerObject()) + .map((response) => { + return new AttributeModel(response); + }); + } + + updateAttribute = (componentType: string, componentId: string, attribute: AttributeModel): Observable => { + const payload = attribute.convertToServerObject(); + + return this.http.put(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/attributes/' + attribute.uniqueId, payload) + .map((response) => { + return new AttributeModel(response); + }); + } + + // Async Methods + addAttributeAsync = async (componentType: string, componentId: string, attribute: AttributeModel): Promise => { + return this.addAttribute(componentType, componentId, attribute).toPromise(); + } + + updateAttributeAsync = async (componentType: string, componentId: string, attribute: AttributeModel): Promise => { + return this.updateAttribute(componentType, componentId, attribute).toPromise(); + } + + deleteAttributeAsync = async (componentType: string, componentId: string, attribute: AttributeModel): Promise => { + return this.http.delete(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/attributes/' + attribute.uniqueId, {}).toPromise(); + } + + getArtifactsByType(componentType: string, componentId: string, artifactsType: ArtifactGroupType) { + return this.getComponentDataByFieldsName(componentType, componentId, [this.convertArtifactTypeToUrl(artifactsType)]); + } + + getServiceConsumptionData(componentType: string, componentId: string): Observable { + return this.getComponentDataByFieldsName(componentType, componentId, [ + // COMPONENT_FIELDS.COMPONENT_INSTANCES_INTERFACES, + COMPONENT_FIELDS.COMPONENT_INSTANCES_PROPERTIES, + // COMPONENT_FIELDS.COMPONENT_INSTANCES_INPUTS, + COMPONENT_FIELDS.COMPONENT_INPUTS, + COMPONENT_FIELDS.COMPONENT_INSTANCES, + COMPONENT_FIELDS.COMPONENT_CAPABILITIES + ]); + } + + getServiceConsumptionInputs(componentMetaDataId: string, serviceInstanceId: string, interfaceId: string, operation: OperationModel): Observable { + return this.http.get + (this.baseUrl + 'services/' + componentMetaDataId + '/consumption/' + serviceInstanceId + '/interfaces/' + interfaceId + '/operations/' + operation.uniqueId + '/inputs'); + } + + createOrUpdateServiceConsumptionInputs(componentMetaDataId: string, serviceInstanceId: string, consumptionInputsList: Array<{[id: string]: ConsumptionInput[]}>): Observable { + return this.http.post(this.baseUrl + 'services/' + componentMetaDataId + '/consumption/' + serviceInstanceId, consumptionInputsList); + } + + getServiceFilterConstraints(componentType: string, componentId: string): Observable { + return this.getComponentDataByFieldsName(componentType, componentId, [SERVICE_FIELDS.NODE_FILTER]); + } + + getComponentInstanceProperties(componentType: string, componentId: string): Observable { + return this.getComponentDataByFieldsName(componentType, componentId, [COMPONENT_FIELDS.COMPONENT_INSTANCES_PROPERTIES]); + } + + createServiceFilterConstraints(componentMetaDataId: string, componentInstanceId: string, constraint: ConstraintObject): Observable { + return this.http.post(this.baseUrl + 'services/' + componentMetaDataId + '/resourceInstances/' + componentInstanceId + '/nodeFilter', constraint); + } + + updateServiceFilterConstraints(componentMetaDataId: string, componentInstanceId: string, constraints: ConstraintObject[]):Observable { + return this.http.put(this.baseUrl + 'services/' + componentMetaDataId + '/resourceInstances/' + componentInstanceId + '/nodeFilter', constraints) + } + + deleteServiceFilterConstraints(componentMetaDataId: string, componentInstanceId: string, constraintIndex: number): Observable{ + return this.http.delete(this.baseUrl + 'services/' + componentMetaDataId + '/resourceInstances/' + componentInstanceId + '/nodeFilter/' + constraintIndex) + } + + deletePolicy(component: Component, policy: PolicyInstance): Observable { + return this.http.put(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/policies/' + policy.uniqueId + '/undeclare', policy) + } + + createListInput(componentId: string, input: any, isSelf: boolean): Observable { + let inputs: any; + if (isSelf) { + // change componentInstanceProperties -> serviceProperties + inputs = { + componentInstInputsMap: { + serviceProperties: input.componentInstInputsMap.componentInstanceProperties + }, + listInput: input.listInput + }; + } else { + inputs = input; + } + return this.http.post(this.baseUrl + 'services/' + componentId + '/create/listInput', inputs); + } + + createPolicy(component: Component, policiesToCreate: InstancePropertiesAPIMap, isSelf: boolean): Observable { + const policiesList = + isSelf ? + // tslint:disable-next-line:object-literal-key-quotes + {'componentPropertiesToPolicies': { + ...policiesToCreate.componentInstanceProperties + } + } : + // tslint:disable-next-line:object-literal-key-quotes + {'componentInstancePropertiesToPolicies': { + ...policiesToCreate.componentInstanceProperties + } + }; + return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/create/policies', policiesList); + } + + protected getComponentDataByFieldsName(componentType: string, componentId: string, fields: string[]): Observable { + let params: HttpParams = new HttpParams(); + _.forEach(fields, (field: string): void => { + params = params.append(API_QUERY_PARAMS.INCLUDE, field); + }); + // tslint:disable-next-line:object-literal-shorthand + return this.http.get(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/filteredDataByParams', {params: params}) + .map((res) => { + return componentType === ComponentType.SERVICE ? new ServiceGenericResponse().deserialize(res) : + new ComponentGenericResponse().deserialize(res); + }); + } + + private getServerTypeUrl = (componentType: string): string => { + switch (componentType) { + case ComponentType.SERVICE: + case ComponentType.SERVICE_PROXY: + return ServerTypeUrl.SERVICES; + default: + return ServerTypeUrl.RESOURCES; + } + } + + private convertArtifactTypeToUrl = (artifactType: ArtifactGroupType): string => { + switch (artifactType) { + case ArtifactGroupType.TOSCA: + return COMPONENT_FIELDS.COMPONENT_TOSCA_ARTIFACTS; + case ArtifactGroupType.INFORMATION: + return COMPONENT_FIELDS.COMPONENT_INFORMATIONAL_ARTIFACTS; + case ArtifactGroupType.DEPLOYMENT: + return COMPONENT_FIELDS.COMPONENT_DEPLOYMENT_ARTIFACTS; + case ArtifactGroupType.SERVICE_API: + return COMPONENT_FIELDS.SERVICE_API_ARTIFACT; + } + } + + // createCapability(component: Component, capabilityData: Capability): Observable { + createCapability(type: string, uniqueId: string, capabilityData: Capability): Observable { + let capBEObj = { + 'capabilities': { + [capabilityData.type]: [capabilityData] + } + }; + return this.http.post(this.baseUrl + type + uniqueId + '/capabilities', capBEObj); + } + + updateCapability(type: string, uniqueId: string, capabilityData: Capability): Observable { + let capBEObj = { + 'capabilities': { + [capabilityData.type]: [capabilityData] + } + }; + return this.http.put(this.baseUrl + type + uniqueId + '/capabilities', capBEObj); + } + + deleteCapability(component: Component, capId: string): Observable { + return this.http.delete(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/capabilities/' + capId); + } + + createRequirement(type: string, uniqueId: string, requirementData: Requirement): Observable { + let reqBEObj = { + 'requirements': { + [requirementData.capability]: [requirementData] + } + }; + return this.http.post(this.baseUrl + type + uniqueId + '/requirements', reqBEObj); + } + + updateRequirement(type: string, uniqueId: string, requirementData: Requirement): Observable { + let reqBEObj = { + 'requirements': { + [requirementData.capability]: [requirementData] + } + }; + return this.http.put(this.baseUrl + type + uniqueId + '/requirements', reqBEObj); + } + + deleteRequirement(component: Component, reqId: string): Observable { + return this.http.delete(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/requirements/' + reqId); + } +} diff --git a/catalog-ui/src/app/ng2/services/config.service.ts b/catalog-ui/src/app/ng2/services/config.service.ts index 11fe395811..2b9b49cf62 100644 --- a/catalog-ui/src/app/ng2/services/config.service.ts +++ b/catalog-ui/src/app/ng2/services/config.service.ts @@ -16,62 +16,80 @@ * */ -import { Injectable, Inject } from '@angular/core'; -import { Http, Response } from '@angular/http'; +import { HttpClient } from '@angular/common/http'; +import { Inject, Injectable, Injector } from '@angular/core'; +import { IAppConfigurtaion, Plugins, PluginsConfiguration, ValidationConfiguration, Validations } from 'app/models'; +import { IApi } from 'app/models/app-config'; import 'rxjs/add/operator/toPromise'; -import {IAppConfigurtaion, ValidationConfiguration, Validations, Plugins, PluginsConfiguration} from "app/models"; -import {IApi} from "app/models/app-config"; -import {SdcConfigToken, ISdcConfig} from "../config/sdc-config.config"; +import { ISdcConfig, SdcConfigToken } from '../config/sdc-config.config'; +import { CacheService } from './cache.service'; @Injectable() export class ConfigService { - private baseUrl; public configuration: IAppConfigurtaion; - public api:IApi; + public api: IApi; + private baseUrl; + + constructor( + @Inject(SdcConfigToken) private sdcConfig: ISdcConfig, + private cacheService: CacheService, + private injector: Injector, + private http: HttpClient + ) { + this.api = this.sdcConfig.api; + this.baseUrl = this.api.root + this.sdcConfig.api.component_api_root; + } - constructor(private http: Http, @Inject(SdcConfigToken) private sdcConfig:ISdcConfig) { - this.api = this.sdcConfig.api; - this.baseUrl = this.api.root + this.sdcConfig.api.component_api_root; + loadSdcSetupData = (): Promise => { + const url: string = this.api.root + this.api.GET_SDC_Setup_Data; + const promise: Promise = this.http.get(url).toPromise(); + promise.then((response) => { + this.cacheService.set('version', response.version); + this.cacheService.set('serviceCategories', response.categories.serviceCategories); + this.cacheService.set('resourceCategories', response.categories.resourceCategories); + this.cacheService.set('UIConfiguration', response.configuration); + }); + return promise; } loadValidationConfiguration(): Promise { - let url: string = this.sdcConfig.validationConfigPath; - let promise: Promise = this.http.get(url).map((res: Response) => res.json()).toPromise(); + const url: string = this.sdcConfig.validationConfigPath; + const promise: Promise = this.http.get(url).toPromise(); promise.then((validationData: Validations) => { ValidationConfiguration.validation = validationData; + this.cacheService.set('validation', validationData); }).catch((ex) => { console.error('Error loading validation.json configuration file, using fallback data', ex); - let fallback:Validations = { - "propertyValue": { - "max": 2500, - "min": 0 + const fallback = { + propertyValue: { + max: 2500, + min: 0 }, - - "validationPatterns": { - "string": "^[\\sa-zA-Z0-9+-]+$", - "comment": "^[\\sa-zA-Z0-9+-_\\{\\}\"]+$", - "integer": "^(([-+]?\\d+)|([-+]?0x[0-9a-fA-F]+))$" + validationPatterns: { + string: '^[\\sa-zA-Z0-9+-]+$', + stringOrEmpty: '^[\\sa-zA-Z0-9&-]*$', + comment: '^[\\sa-zA-Z0-9+-_\\{\\}"]+$', + integer: '^(([-+]?\\d+)|([-+]?0x[0-9a-fA-F]+))$' } }; - ValidationConfiguration.validation = fallback; - + this.cacheService.set('validation', fallback); }); return promise; } - loadPluginsConfiguration(): Promise { - let url:string = this.api.no_proxy_root + this.api.GET_plugins_configuration; - let promise: Promise = this.http.get(url).map((res: Response) => res.json()).toPromise(); + loadPluginsConfiguration = (): Promise => { + const url: string = this.api.no_proxy_root + this.api.GET_plugins_configuration; + const promise: Promise = this.http.get(url).toPromise(); return new Promise((resolve) => { promise.then((pluginsData: Plugins) => { PluginsConfiguration.plugins = pluginsData; resolve(); }).catch((ex) => { - console.error("Error loading plugins configuration from FE", ex); + console.error('Error loading plugins configuration from FE', ex); PluginsConfiguration.plugins = [] as Plugins; resolve(); diff --git a/catalog-ui/src/app/ng2/services/cookie.service.ts b/catalog-ui/src/app/ng2/services/cookie.service.ts index 2a783fdd48..61d13186fa 100644 --- a/catalog-ui/src/app/ng2/services/cookie.service.ts +++ b/catalog-ui/src/app/ng2/services/cookie.service.ts @@ -19,7 +19,7 @@ */ import {Injectable, Inject} from '@angular/core'; -import {IAppConfigurtaion, ICookie} from "../../models/app-config"; +import {ICookie} from "../../models/app-config"; import {SdcConfigToken, ISdcConfig} from "../config/sdc-config.config"; @Injectable() diff --git a/catalog-ui/src/app/ng2/services/data-type.service.ts b/catalog-ui/src/app/ng2/services/data-type.service.ts index cabaccd1d5..0559f35ae2 100644 --- a/catalog-ui/src/app/ng2/services/data-type.service.ts +++ b/catalog-ui/src/app/ng2/services/data-type.service.ts @@ -20,9 +20,9 @@ import * as _ from "lodash"; import { Injectable } from '@angular/core'; -import { DataTypeModel, DataTypesMap, PropertyBEModel, PropertyFEModel, DerivedFEProperty, DerivedFEPropertyMap } from "app/models"; +import { DataTypeModel, DataTypesMap, PropertyFEModel, DerivedFEProperty} from "app/models"; import { DataTypesService } from "app/services/data-types-service"; -import { PROPERTY_DATA, PROPERTY_TYPES } from "app/utils"; +import { PROPERTY_DATA } from "app/utils"; /** This is a new service for NG2, to eventually replace app/services/data-types-service.ts * @@ -32,13 +32,16 @@ import { PROPERTY_DATA, PROPERTY_TYPES } from "app/utils"; @Injectable() export class DataTypeService { - private dataTypes: DataTypesMap; + public dataTypes: DataTypesMap; constructor(private dataTypeService: DataTypesService) { this.dataTypes = dataTypeService.getAllDataTypes(); //This should eventually be replaced by an NG2 call to the backend instead of utilizing Angular1 downgraded component. } public getDataTypeByTypeName(typeName: string): DataTypeModel { + if(!this.dataTypes){ + this.dataTypes = this.dataTypeService.getAllDataTypes(); + } if (!this.dataTypes[typeName]) console.log("MISSING Datatype: " + typeName); return this.dataTypes[typeName]; } @@ -47,6 +50,13 @@ export class DataTypeService { return this.dataTypes; } + public getConstraintsByParentTypeAndUniqueID(rootPropertyType, propertyName){ + // const property = this.dataTypes[rootPropertyType].properties.filter(property => + // property.name == propertyName); + // return property[0] && property[0].constraints ? property[0].constraints[0].validValues : null; + return null; + } + public getDerivedDataTypeProperties(dataTypeObj: DataTypeModel, propertiesArray: Array, parentName: string) { //push all child properties to array diff --git a/catalog-ui/src/app/ng2/services/event-bus.service.ts b/catalog-ui/src/app/ng2/services/event-bus.service.ts index cc53d7978b..2a15ca25db 100644 --- a/catalog-ui/src/app/ng2/services/event-bus.service.ts +++ b/catalog-ui/src/app/ng2/services/event-bus.service.ts @@ -1,5 +1,5 @@ import {Injectable} from '@angular/core'; -import {BasePubSub, IPubSubEvent} from 'sdc-pubsub'; +import {BasePubSub, IPubSubEvent} from "sdc-pubsub"; @Injectable() export class EventBusService extends BasePubSub { diff --git a/catalog-ui/src/app/ng2/services/file-utils.service.ts b/catalog-ui/src/app/ng2/services/file-utils.service.ts new file mode 100644 index 0000000000..57897492b0 --- /dev/null +++ b/catalog-ui/src/app/ng2/services/file-utils.service.ts @@ -0,0 +1,48 @@ +import { Injectable } from "@angular/core"; +import { WindowRef } from "./window.service"; + +@Injectable() +export class FileUtilsService { + constructor(private windowRef: WindowRef){} + + public byteCharactersToBlob = (byteCharacters, contentType):any => { + contentType = contentType || ''; + let sliceSize = 1024; + let bytesLength = byteCharacters.length; + let slicesCount = Math.ceil(bytesLength / sliceSize); + let byteArrays = new Array(slicesCount); + + for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) { + let begin = sliceIndex * sliceSize; + let end = Math.min(begin + sliceSize, bytesLength); + + let bytes = new Array(end - begin); + for (let offset = begin, i = 0; offset < end; ++i, ++offset) { + bytes[i] = byteCharacters[offset].charCodeAt(0); + } + byteArrays[sliceIndex] = new Uint8Array(bytes); + } + return new Blob(byteArrays, {type: contentType}); + }; + + public base64toBlob = (base64Data, contentType):any => { + let byteCharacters = atob(base64Data); + return this.byteCharactersToBlob(byteCharacters, contentType); + }; + + public downloadFile = (blob, fileName):void=> { + let url = this.windowRef.nativeWindow.URL.createObjectURL(blob); + let downloadLink = document.createElement("a"); + + downloadLink.setAttribute('href', url); + downloadLink.setAttribute('download', fileName); + document.body.appendChild(downloadLink); + + var clickEvent = new MouseEvent("click", { + "view": window, + "bubbles": true, + "cancelable": true + }); + downloadLink.dispatchEvent(clickEvent); + } +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/services/gab.service.ts b/catalog-ui/src/app/ng2/services/gab.service.ts index d903d20ade..b62c566dd6 100644 --- a/catalog-ui/src/app/ng2/services/gab.service.ts +++ b/catalog-ui/src/app/ng2/services/gab.service.ts @@ -18,12 +18,13 @@ * ============LICENSE_END========================================================= */ -import {Injectable, Inject} from "@angular/core"; -import {Response} from '@angular/http'; -import {HttpService} from "./http.service"; -import {SdcConfigToken, ISdcConfig} from "../config/sdc-config.config"; -import {Observable} from "rxjs"; +import { HttpClient } from '@angular/common/http'; +import { Inject, Injectable } from '@angular/core'; +import { Response } from '@angular/http'; +import { Observable } from 'rxjs'; +import { ISdcConfig, SdcConfigToken } from '../config/sdc-config.config'; +// tslint:disable-next-line:interface-name export interface IServerResponse { data: [{ [key: string]: string }]; } @@ -36,24 +37,25 @@ export class GabRequest { } } +// tslint:disable-next-line:max-classes-per-file @Injectable() export class GabService { baseUrl: string; gabUrl: string; - constructor(@Inject(SdcConfigToken) sdcConfig: ISdcConfig, private http: HttpService) { + constructor(@Inject(SdcConfigToken) sdcConfig: ISdcConfig, protected http: HttpClient) { this.baseUrl = sdcConfig.api.root; this.gabUrl = sdcConfig.api.POST_GAB_Search; } public getArtifact(artifactUniqueId: string, resourceId: string, columns: string[]): Observable { - let finalUrl: string = this.baseUrl + this.gabUrl; - let request: GabRequest = { + const finalUrl: string = this.baseUrl + this.gabUrl; + const request: GabRequest = { fields: columns, parentId: resourceId, - artifactUniqueId: artifactUniqueId + artifactUniqueId }; - return this.http.post(finalUrl, request); + return this.http.post(finalUrl, request); } } \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/services/groups.service.ts b/catalog-ui/src/app/ng2/services/groups.service.ts index e3b3d85b50..8b2bcd3415 100644 --- a/catalog-ui/src/app/ng2/services/groups.service.ts +++ b/catalog-ui/src/app/ng2/services/groups.service.ts @@ -1,11 +1,11 @@ import {IZoneInstanceAssignment} from '../../models/graph/zones/zone-instance'; import {Injectable, Inject} from "@angular/core"; import {Observable} from "rxjs/Observable"; -import {HttpService} from "./http.service"; import {SdcConfigToken, ISdcConfig} from "../config/sdc-config.config"; import {GroupInstance} from '../../models/graph/zones/group-instance'; import {UiBaseObject} from "../../models/ui-models/ui-base-object"; import {IZoneService} from "../../models/graph/zones/zone"; +import { HttpClient } from '@angular/common/http'; @Injectable() export class GroupsService implements IZoneService { @@ -17,13 +17,13 @@ export class GroupsService implements IZoneService { 'SERVICE': 'services' } - constructor(private http:HttpService, @Inject(SdcConfigToken) sdcConfig:ISdcConfig) { + constructor(private http: HttpClient, @Inject(SdcConfigToken) sdcConfig:ISdcConfig) { this.baseUrl = sdcConfig.api.root; } - public createGroupInstance(componentType:string, componentUniqueId:string, groupType:string) { - return this.http.post(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[componentType.toUpperCase()] + '/' + componentUniqueId + '/groups/' + groupType, {}).map(resp => { - return resp.json(); + public createGroupInstance(componentType:string, componentUniqueId:string, groupType:string): Observable{ + return this.http.post(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[componentType.toUpperCase()] + '/' + componentUniqueId + '/groups/' + groupType, {}).map(resp => { + return new GroupInstance(resp); }); }; @@ -40,8 +40,7 @@ export class GroupsService implements IZoneService { } public updateGroupMembers(topologyTemplateType:string, topologyTemplateId:string, groupId:string, members:Array):Observable> { - return this.http.post(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/groups/' + groupId + '/members', members) - .map(response => response.json()); + return this.http.post>(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/groups/' + groupId + '/members', members); } public updateMembers(topologyTemplateType:string, topologyTemplateId:string, groupId:string, members:Array):Observable> { @@ -50,22 +49,18 @@ export class GroupsService implements IZoneService { } public getSpecificGroup(topologyTemplateType:string, topologyTemplateId:string, groupId:string):Observable { - return this.http.get(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/groups/' + groupId) + return this.http.get(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/groups/' + groupId) .map(res => { - return new GroupInstance(res.json()); + return new GroupInstance(res); }); } public updateName(topologyTemplateType:string, topologyTemplateId:string, groupId:string, newName:string):Observable { - return this.http.put(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/groups/' + groupId, {name: newName}).map(resp => { - return resp.json(); - }); + return this.http.put(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/groups/' + groupId, {name: newName}); }; public deleteGroup(topologyTemplateType:string, topologyTemplateId:string, groupId:string) { - return this.http.delete(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/groups/' + groupId).map(resp => { - return resp.json(); - }); + return this.http.delete(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/groups/' + groupId); }; public updateZoneInstanceAssignments(topologyTemplateType:string, topologyTemplateId:string, policyId:string, members:Array):Observable { @@ -75,4 +70,6 @@ export class GroupsService implements IZoneService { public deleteZoneInstance(topologyTemplateType:string, topologyTemplateId:string, policyId:string):Observable { return this.deleteGroup(topologyTemplateType, topologyTemplateId, policyId); }; -} \ No newline at end of file + + +} diff --git a/catalog-ui/src/app/ng2/services/home.service.ts b/catalog-ui/src/app/ng2/services/home.service.ts new file mode 100644 index 0000000000..c472aa80c1 --- /dev/null +++ b/catalog-ui/src/app/ng2/services/home.service.ts @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +import { HttpClient } from '@angular/common/http'; +import { Inject, Injectable } from '@angular/core'; +import { Component, IApi, Resource, Service } from 'app/models'; +import { ComponentFactory } from 'app/utils/component-factory'; +import { Observable } from 'rxjs'; +import { ISdcConfig, SdcConfigToken } from '../config/sdc-config.config'; +import { SharingService } from './sharing.service'; + +// tslint:disable-next-line:interface-name +interface IComponentsArray { + services: Service[]; + resources: Resource[]; +} + +@Injectable() +export class HomeService { + private api: IApi; + private smallObjectAttributes = [ + 'uniqueId', 'name', 'componentType', 'resourceType', 'lastUpdateDate', 'lifecycleState', 'distributionStatus', + 'icon', 'version' + ]; + + constructor(private http: HttpClient, + @Inject(SdcConfigToken) private sdcConfig: ISdcConfig, + private sharingService: SharingService, + private componentFactory: ComponentFactory) { + this.api = sdcConfig.api; + } + + public getAllComponents(smallObjects?: boolean): Observable { + return this.http.get(this.api.root + this.api.GET_element) + .map((response) => { + const componentResponse: IComponentsArray = response; + let componentsList: Component[] = []; + + componentResponse.services && componentResponse.services.forEach((serviceResponse: Service) => { + serviceResponse = (smallObjects) ? _.pick(serviceResponse, this.smallObjectAttributes) : serviceResponse; + const component: Service = this.componentFactory.createService(serviceResponse); + componentsList.push(component); + this.sharingService.addUuidValue(component.uniqueId, component.uuid); + }); + + componentResponse.resources && componentResponse.resources.forEach((resourceResponse: Resource) => { + resourceResponse = (smallObjects) ? _.pick(resourceResponse, this.smallObjectAttributes) : resourceResponse; + const component: Resource = this.componentFactory.createResource(resourceResponse); + componentsList.push(component); + this.sharingService.addUuidValue(component.uniqueId, component.uuid); + }); + + componentsList = _.orderBy(componentsList, ['lastUpdateDate'], ['desc']); + + return componentsList; + }); + } +} diff --git a/catalog-ui/src/app/ng2/services/http-hepler.service.ts b/catalog-ui/src/app/ng2/services/http-hepler.service.ts new file mode 100644 index 0000000000..2b11067a24 --- /dev/null +++ b/catalog-ui/src/app/ng2/services/http-hepler.service.ts @@ -0,0 +1,31 @@ +import { Injectable, Inject } from "@angular/core"; +import { Dictionary } from "../../utils/dictionary/dictionary"; +import { SharingService } from "../services/sharing.service"; +import { SdcConfigToken, ISdcConfig } from "../config/sdc-config.config"; + + +@Injectable() +export class HttpHelperService { + constructor( private sharingService: SharingService, + @Inject(SdcConfigToken) private sdcConfig: ISdcConfig){} + + public getUuidValue = (url: string): string => { + let map: Dictionary = this.sharingService.getUuidMap(); + if (map && url.indexOf(this.sdcConfig.api.root) > 0) { + map.forEach((key: string) => { + if (url.indexOf(key) !== -1) { + return this.sharingService.getUuidValue(key); + } + }); + } + return ''; + } + public static replaceUrlParams(url: string, urlParams: { [index: string]: any }): string { + return url.replace(/:(\w+)/g, (m, p1): string => urlParams[p1] || ''); + } + public static getHeaderMd5 = (object:any):string => { + let componentString:string = JSON.stringify(object); + let md5Result = md5(componentString).toLowerCase(); + return btoa(md5Result); + }; +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/services/http.service.ts b/catalog-ui/src/app/ng2/services/http.service.ts deleted file mode 100644 index 2785688ace..0000000000 --- a/catalog-ui/src/app/ng2/services/http.service.ts +++ /dev/null @@ -1,100 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -import {Injectable, Inject} from '@angular/core'; -import {Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers} from '@angular/http'; -import {Observable} from 'rxjs/Observable'; -import {UUID} from 'angular2-uuid'; -import 'rxjs/add/operator/map'; -import 'rxjs/add/operator/catch'; -import 'rxjs/add/observable/throw'; -import {Dictionary} from "../../utils/dictionary/dictionary"; -import {SharingService, CookieService} from "app/services"; -import { ModalService } from "app/ng2/services/modal.service"; -import { ServerErrorResponse } from "app/models"; -import {ErrorMessageComponent} from "../components/ui/modal/error-message/error-message.component"; -import {SdcConfigToken, ISdcConfig} from "../config/sdc-config.config"; - -@Injectable() -export class HttpService extends Http { - - constructor(backend: XHRBackend, options: RequestOptions, private sharingService: SharingService, private cookieService: CookieService, private modalService: ModalService, @Inject(SdcConfigToken) private sdcConfig:ISdcConfig) { - super(backend, options); - this._defaultOptions.withCredentials = true; - this._defaultOptions.headers.append(cookieService.getUserIdSuffix(), cookieService.getUserId()); - } - - request(request:string|Request, options?:RequestOptionsArgs):Observable { - /** - * For every request to the server, that the service id, or resource id is sent in the URL, need to pass UUID in the header. - * Check if the unique id exists in uuidMap, and if so get the UUID and add it to the header. - */ - if (typeof request === 'string') { // meaning we have to add the token to the options, not in url - if (!options) { - // make option object - options = {headers: new Headers()}; - } - - var uuidValue = this.getUuidValue(request); - if(uuidValue!= ''){ - options.headers['X-ECOMP-ServiceID'] = uuidValue; - - } - options.headers.set('X-ECOMP-RequestID', UUID.UUID()); - - } else { - // we have to add the token to the url object - var uuidValue = this.getUuidValue((request).url); - if(uuidValue!= ''){ - request.headers.set('X-ECOMP-ServiceID',uuidValue); - - } - request.headers.set('X-ECOMP-RequestID', UUID.UUID()); - } - return super.request(request, options).catch((err) => this.catchError(err)); - } - - private getUuidValue = (url: string) :string => { - let map:Dictionary = this.sharingService.getUuidMap(); - if (map && url.indexOf(this.sdcConfig.api.root) > 0) { - map.forEach((key:string) => { - if (url.indexOf(key) !== -1) { - return this.sharingService.getUuidValue(key); - } - }); - } - return ''; - } - - private catchError = (response: Response): Observable => { - - let modalInstance = this.modalService.createErrorModal("OK"); - let errorResponse: ServerErrorResponse = new ServerErrorResponse(response); - this.modalService.addDynamicContentToModal(modalInstance, ErrorMessageComponent, errorResponse); - modalInstance.instance.open(); - - return Observable.throw(response); - }; - - public static replaceUrlParams(url:string, urlParams:{[index:string]:any}):string { - return url.replace(/:(\w+)/g, (m, p1):string => urlParams[p1] || ''); - } - -} diff --git a/catalog-ui/src/app/ng2/services/modules.service.ts b/catalog-ui/src/app/ng2/services/modules.service.ts new file mode 100644 index 0000000000..857f0718d6 --- /dev/null +++ b/catalog-ui/src/app/ng2/services/modules.service.ts @@ -0,0 +1,34 @@ +import {Inject, Injectable} from "@angular/core"; +import {HttpClient} from "@angular/common/http"; +import {ISdcConfig, SdcConfigToken} from "../config/sdc-config.config"; +import {DisplayModule, Module} from "../../models/modules/base-module"; +import {Observable} from "rxjs/Observable"; +import {ServerTypeUrl} from "../../utils/constants"; + +@Injectable() +export class ModulesService { + + protected baseUrl; + + constructor(private http: HttpClient, @Inject(SdcConfigToken) sdcConfig: ISdcConfig) { + this.baseUrl = sdcConfig.api.root + sdcConfig.api.component_api_root; + } + + getComponentInstanceModule = (topologyTemplateType: string, topologyTemplateId: string, componentInstanceId: string, moduleId: string):Observable => { + return this.http.get(this.baseUrl + ServerTypeUrl.toServerTypeUrl(topologyTemplateType) + "/" + topologyTemplateId + "/resourceInstance/" + componentInstanceId + "/groupInstance/" + moduleId) + .map((response) => { + return new DisplayModule(response); + }) + }; + + getModuleForDisplay = (topologyTemplateType: string, topologyTemplateId: string, moduleId: string):Observable => { + return this.http.get(this.baseUrl + ServerTypeUrl.toServerTypeUrl(topologyTemplateType) + "/" + topologyTemplateId + "/groups/" + moduleId) + .map((response) => { + return new DisplayModule(response); + }) + }; + + public updateModuleMetadata = (topologyTemplateType: string, topologyTemplateId: string, module: Module):Observable => { + return this.http.put(this.baseUrl + ServerTypeUrl.toServerTypeUrl(topologyTemplateType) + "/" + topologyTemplateId + "/groups/" + module.uniqueId + "/metadata", module) + } +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/services/onboarding.service.ts b/catalog-ui/src/app/ng2/services/onboarding.service.ts new file mode 100644 index 0000000000..0ec4875d91 --- /dev/null +++ b/catalog-ui/src/app/ng2/services/onboarding.service.ts @@ -0,0 +1,151 @@ +/** + * Created by rc2122 on 6/4/2018. + */ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +'use strict'; +import {Inject, Injectable} from "@angular/core"; +import {SdcConfigToken, ISdcConfig} from "app/ng2/config/sdc-config.config"; +import {Observable} from "rxjs/Observable"; +import { HttpClient, HttpResponse } from "@angular/common/http"; +import { ComponentFactory } from "../../utils/component-factory"; +import { DEFAULT_ICON, ComponentType } from "../../utils/constants"; +import { ICsarComponent } from "../../models/csar-component"; +import { IApi } from "../../models/app-config"; +import { CacheService } from "./cache.service"; +import { IComponentMetadata, ComponentMetadata } from "../../models/component-metadata"; +import { IMainCategory, ISubCategory } from "../../models/category"; +import { Resource } from "../../models/components/resource"; + +export interface OnboardingComponents { + listCount: number; + results: Array +} + +@Injectable() +export class OnboardingService { + private api:IApi; + + constructor(protected http: HttpClient, + private cacheService:CacheService, + @Inject(SdcConfigToken) sdcConfig:ISdcConfig, + private componentFactory: ComponentFactory) { + this.api = sdcConfig.api; + } + + getOnboardingVSPs = (): Observable> =>{ + return this.http.get(this.api.GET_onboarding).map((onboardingVSPs) =>{ + return onboardingVSPs.results + }); + } + + getOnboardingComponents = ():Observable> => { + return this.getOnboardingVSPs().map((onboardingComponents) => { + let componentsMetadataList: Array = new Array(); + onboardingComponents.forEach((obc:ICsarComponent) => { + let componentMetaData: ComponentMetadata = this.createFromCsarComponent(obc); + componentsMetadataList.push(componentMetaData); + }); + return componentsMetadataList; + }); + }; + + public createFromCsarComponent = (csar:ICsarComponent): ComponentMetadata => { + let newMetadata = new ComponentMetadata(); + newMetadata.name = csar.vspName; + + /** + * Onboarding CSAR contains category and sub category that are uniqueId. + * Need to find the category and sub category and extract the name from them. + * First concat all sub categories to one array. + * Then find the selected sub category and category. + * @type {any} + */ + let availableCategories = angular.copy(this.cacheService.get('resourceCategories')); + let allSubs = []; + _.each(availableCategories, (main:IMainCategory)=> { + if (main.subcategories) { + allSubs = allSubs.concat(main.subcategories); + } + }); + + let selectedCategory:IMainCategory = _.find(availableCategories, function (main:IMainCategory) { + return main.uniqueId === csar.category; + }); + + let selectedSubCategory:ISubCategory = _.find(allSubs, (sub:ISubCategory)=> { + return sub.uniqueId === csar.subCategory; + }); + + // Build the categories and sub categories array (same format as component category) + let categories:Array = new Array(); + let subcategories:Array = new Array(); + if (selectedCategory && selectedSubCategory) { + subcategories.push(selectedSubCategory); + selectedCategory.subcategories = subcategories; + categories.push(selectedCategory); + } + + // Fill the component with details from CSAR + + newMetadata.categories = categories; + newMetadata.vendorName = csar.vendorName; + newMetadata.vendorRelease = csar.vendorRelease; + newMetadata.csarUUID = csar.packageId; + newMetadata.csarPackageType = csar.packageType; + newMetadata.csarVersion = csar.version; + newMetadata.packageId = csar.packageId; + newMetadata.description = csar.description; + newMetadata.selectedCategory = selectedCategory && selectedSubCategory ? selectedCategory.name + "_#_" + selectedSubCategory.name : ''; + newMetadata.filterTerm = newMetadata.name + ' ' + newMetadata.description + ' ' + newMetadata.vendorName + ' ' + newMetadata.csarVersion; + newMetadata.resourceType = "VF"; + newMetadata.componentType = ComponentType.RESOURCE; + newMetadata.tags = []; + newMetadata.icon = DEFAULT_ICON; + newMetadata.iconSprite = "sprite-resource-icons"; + return newMetadata; + }; + + downloadOnboardingCsar = (packageId:string):Observable> => { + return this.http.get(this.api.GET_onboarding + "/" + packageId, {observe: 'response', responseType: 'blob'}); + }; + + getComponentFromCsarUuid = (csarUuid:string):Observable => { + return this.http.get(this.api.root + this.api.GET_component_from_csar_uuid.replace(':csar_uuid', csarUuid)) + .map((response: any) => { + // If the status is 400, this means that the component not found. + // I do not want to return error from server, because a popup will appear in client with the error. + // So returning success (200) with status 400. + if (response.status !== 400) { + let componentMetadata = new ComponentMetadata(); + componentMetadata = response; + return componentMetadata; + } + }); + }; + + //TODO remove when workspace page convert to angular5 + convertMetaDataToComponent(componentMetadata: ComponentMetadata) { + let newResource: Resource = this.componentFactory.createEmptyComponent(ComponentType.RESOURCE); + newResource.setComponentMetadata(componentMetadata); + return newResource; + } +} diff --git a/catalog-ui/src/app/ng2/services/plugins.service.ts b/catalog-ui/src/app/ng2/services/plugins.service.ts index 2a3b68fe25..0f71eee1f0 100644 --- a/catalog-ui/src/app/ng2/services/plugins.service.ts +++ b/catalog-ui/src/app/ng2/services/plugins.service.ts @@ -1,40 +1,40 @@ -import { Injectable, Inject } from '@angular/core'; +import {Inject, Injectable} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import {Http, Response} from '@angular/http'; -import {IApi, IAppConfigurtaion, Plugin, Plugins, PluginsConfiguration} from "app/models"; +import {IApi, IAppConfigurtaion, Plugin, PluginsConfiguration} from "app/models"; import {ISdcConfig, SdcConfigToken} from "../config/sdc-config.config"; @Injectable() export class PluginsService { - private baseUrl; public configuration: IAppConfigurtaion; public api: IApi; + private baseUrl; - constructor(private http: Http, @Inject(SdcConfigToken) private sdcConfig:ISdcConfig) { + constructor(private http: Http, @Inject(SdcConfigToken) private sdcConfig: ISdcConfig) { this.api = this.sdcConfig.api; this.baseUrl = this.api.root + this.sdcConfig.api.component_api_root; } public getPluginByStateUrl = (stateUrl: string) => { - let pluginKey: any = _.findKey(PluginsConfiguration.plugins, (pluginConfig: Plugin) =>{ - return pluginConfig.pluginStateUrl === stateUrl; + let pluginKey: any = _.findKey(PluginsConfiguration.plugins, (pluginConfig: Plugin) => { + return pluginConfig.pluginStateUrl === stateUrl; }); return PluginsConfiguration.plugins[pluginKey]; }; - public isPluginDisplayedInContext = (plugin: Plugin ,userRole: string, contextType: string) => { + public isPluginDisplayedInContext = (plugin: Plugin, userRole: string, contextType: string) => { return plugin.pluginDisplayOptions["context"] && - plugin.pluginDisplayOptions["context"].displayRoles.includes(userRole) && - plugin.pluginDisplayOptions["context"].displayContext.indexOf(contextType) !== -1 + plugin.pluginDisplayOptions["context"].displayRoles.includes(userRole) && + plugin.pluginDisplayOptions["context"].displayContext.indexOf(contextType) !== -1 }; public isPluginOnline = (pluginId: string): Observable => { - let url:string = this.api.no_proxy_root + this.api.GET_plugin_online_state.replace(':pluginId', pluginId); + let url: string = this.api.no_proxy_root + this.api.GET_plugin_online_state.replace(':pluginId', pluginId); return this.http.get(url).map((res: Response) => { return res.json() }) - .catch(error => Observable.of(false)); + .catch(error => Observable.of(false)); } } diff --git a/catalog-ui/src/app/ng2/services/policies.service.ts b/catalog-ui/src/app/ng2/services/policies.service.ts index 3675a7b9ab..a1a9013303 100644 --- a/catalog-ui/src/app/ng2/services/policies.service.ts +++ b/catalog-ui/src/app/ng2/services/policies.service.ts @@ -20,13 +20,13 @@ import {Injectable, Inject} from "@angular/core"; import {Observable} from "rxjs/Observable"; -import {HttpService} from "./http.service"; import {SdcConfigToken, ISdcConfig} from "../config/sdc-config.config"; import {PolicyInstance, PolicyTargetsRequest} from '../../models/graph/zones/policy-instance'; import {IZoneInstanceAssignment} from "../../models/graph/zones/zone-instance"; import {IZoneService} from "../../models/graph/zones/zone"; import {TargetUiObject} from "../../models/ui-models/ui-target-object"; import {TargetOrMemberType} from "../../utils/constants"; +import { HttpClient } from "@angular/common/http"; @Injectable() @@ -38,14 +38,12 @@ export class PoliciesService implements IZoneService { 'SERVICE': 'services' } - constructor(private http:HttpService, @Inject(SdcConfigToken) sdcConfig:ISdcConfig) { + constructor(private http: HttpClient, @Inject(SdcConfigToken) sdcConfig:ISdcConfig) { this.baseUrl = sdcConfig.api.root; } - public createPolicyInstance(topologyTemplateType:string, topologyTemplateId:string, policyType:string) { - return this.http.post(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/policies/' + policyType, {}).map(resp => { - return resp.json(); - }); + public createPolicyInstance(topologyTemplateType:string, topologyTemplateId:string, policyType:string): Observable { + return this.http.post(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/policies/' + policyType, {}); } public addPolicyTarget(topologyTemplateType:string, topologyTemplateId:string, policy:PolicyInstance, targetId:string, targetType:TargetOrMemberType) { @@ -76,8 +74,8 @@ export class PoliciesService implements IZoneService { } public updatePolicyTargets(topologyTemplateType:string, topologyTemplateId:string, policyId:string, targets:PolicyTargetsRequest): Observable { - return this.http.post(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/policies/' + policyId + '/targets', targets.requestItems) - .map(response => new PolicyInstance(response.json())); + return this.http.post(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/policies/' + policyId + '/targets', targets.requestItems) + .map(response => new PolicyInstance(response)); } public updateTargets(topologyTemplateType:string, topologyTemplateId:string, policyId:string, targets:Array):Observable { @@ -94,22 +92,18 @@ export class PoliciesService implements IZoneService { } public getSpecificPolicy(topologyTemplateType:string, topologyTemplateId:string, policyId:string):Observable { - return this.http.get(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/policies/' + policyId) + return this.http.get(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/policies/' + policyId) .map(res => { - return new PolicyInstance(res.json()); + return new PolicyInstance(res); }); } public updateName(topologyTemplateType:string, topologyTemplateId:string, policyId:string, newName:string):Observable { - return this.http.put(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/policies/' + policyId, {name: newName}).map(res => { - return res.json(); - }); + return this.http.put(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/policies/' + policyId, {name: newName}); }; public deletePolicy(topologyTemplateType:string, topologyTemplateId:string, policyId:string) { - return this.http.delete(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/policies/' + policyId).map(resp => { - return resp.json(); - }); + return this.http.delete(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[topologyTemplateType.toUpperCase()] + '/' + topologyTemplateId + '/policies/' + policyId); }; public updateZoneInstanceAssignments(topologyTemplateType:string, topologyTemplateId:string, policyId:string, targets:Array):Observable{ diff --git a/catalog-ui/src/app/ng2/services/responses/component-generic-response.ts b/catalog-ui/src/app/ng2/services/responses/component-generic-response.ts index d297ea0874..f161babfa6 100644 --- a/catalog-ui/src/app/ng2/services/responses/component-generic-response.ts +++ b/catalog-ui/src/app/ng2/services/responses/component-generic-response.ts @@ -22,12 +22,15 @@ * Created by ob0695 on 4/18/2017. */ -import { ArtifactGroupModel, PropertyModel, PropertiesGroup, InputsGroup, AttributeModel, AttributesGroup, ComponentInstance, OperationModel, - InputBEModel, Module, ComponentMetadata, RelationshipModel, RequirementsGroup, CapabilitiesGroup, InterfaceModel} from "app/models"; +import { ArtifactGroupModel, PropertyModel, PropertiesGroup, AttributeModel, AttributesGroup, ComponentInstance, OperationModel, + InputBEModel, Module, ComponentMetadata, RelationshipModel, RequirementsGroup, CapabilitiesGroup} from "app/models"; import {CommonUtils} from "app/utils"; import {Serializable} from "../utils/serializable"; +import {PropertyBEModel} from "../../../models/properties-inputs/property-be-model"; import { PolicyInstance } from "app/models/graph/zones/policy-instance"; import { GroupInstance } from "../../../models/graph/zones/group-instance"; +import { InputsGroup } from "../../../models/inputs"; +import { InterfaceModel } from "../../../models/operation"; export class ComponentGenericResponse implements Serializable { @@ -40,7 +43,7 @@ export class ComponentGenericResponse implements Serializable; public componentInstances:Array; - public componentInstancesInterfaces:Map>; + public componentInstancesInterfaces: Map>; public inputs:Array; public capabilities:CapabilitiesGroup; public requirements:RequirementsGroup; @@ -75,7 +78,7 @@ export class ComponentGenericResponse implements Serializable { public forwardingPaths: { [key:string]:ForwardingPath } = {}; + public serviceApiArtifacts: ArtifactGroupModel; deserialize (response): ServiceGenericResponse { super.deserialize(response); + this.serviceApiArtifacts = new ArtifactGroupModel(response.serviceApiArtifacts); if(response.forwardingPaths) { _.forEach(response.forwardingPaths, (pathResponse, id) => { let pathId = id; diff --git a/catalog-ui/src/app/ng2/services/sharing.service.ts b/catalog-ui/src/app/ng2/services/sharing.service.ts new file mode 100644 index 0000000000..0a6b8cb1af --- /dev/null +++ b/catalog-ui/src/app/ng2/services/sharing.service.ts @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +import {Injectable} from "@angular/core"; +import {Dictionary} from "app/utils"; + +@Injectable() +export class SharingService { + private uuidMap:Dictionary = new Dictionary(); + + constructor() { + } + + public getUuidValue(uniqueId:string): string { + return this.uuidMap.getValue(uniqueId); + } + + public addUuidValue(uniqueId:string, uuid:string): void { + this.uuidMap.setValue(uniqueId, uuid); + } + + public getUuidMap() :Dictionary { + return this.uuidMap; + } +} diff --git a/catalog-ui/src/app/ng2/services/tosca-types.service.ts b/catalog-ui/src/app/ng2/services/tosca-types.service.ts index 66826c0fef..83b833b1ab 100644 --- a/catalog-ui/src/app/ng2/services/tosca-types.service.ts +++ b/catalog-ui/src/app/ng2/services/tosca-types.service.ts @@ -14,12 +14,19 @@ * permissions and limitations under the License. */ -import {Injectable, Inject} from '@angular/core'; -import {Observable} from 'rxjs/Observable'; -import {HttpService} from './http.service'; -import {SdcConfigToken, ISdcConfig} from "../config/sdc-config.config"; -import {CapabilityTypesMap, NodeTypesMap, RelationshipTypesMap} from "app/models"; -import {Response} from '@angular/http'; +import { HttpClient } from '@angular/common/http'; +import { Inject, Injectable } from '@angular/core'; +import { Response } from '@angular/http'; +import { + CapabilityTypeModel, + CapabilityTypesMap, + IComponentsArray, + NodeTypesMap, + RelationshipTypesMap +} from 'app/models'; +import { Observable } from 'rxjs/Observable'; +import { ISdcConfig, SdcConfigToken } from '../config/sdc-config.config'; +import 'rxjs/add/operator/toPromise'; declare var angular: angular.IAngularStatic; @@ -28,28 +35,20 @@ export class ToscaTypesServiceNg2 { protected baseUrl; - constructor(protected http: HttpService, @Inject(SdcConfigToken) sdcConfig: ISdcConfig) { + constructor(protected http: HttpClient, @Inject(SdcConfigToken) sdcConfig: ISdcConfig) { this.baseUrl = sdcConfig.api.root + sdcConfig.api.component_api_root; } - fetchRelationshipTypes(): Observable { - return this.http.get(this.baseUrl + 'relationshipTypes') - .map((res: Response) => { - return res.json(); - }); + async fetchRelationshipTypes(): Promise { + return this.http.get(this.baseUrl + 'relationshipTypes').toPromise(); } - fetchNodeTypes(): Observable { - return this.http.get(this.baseUrl + 'nodeTypes') - .map((res: Response) => { - return res.json(); - }); + async fetchNodeTypes(): Promise { + return this.http.get(this.baseUrl + 'nodeTypes').toPromise(); } - fetchCapabilityTypes(): Observable { - return this.http.get(this.baseUrl + 'capabilityTypes') - .map((res: Response) => { - return res.json(); - }); + async fetchCapabilityTypes(): Promise{ + return this.http.get(this.baseUrl + 'capabilityTypes').toPromise(); } } + diff --git a/catalog-ui/src/app/ng2/services/user.service.ts b/catalog-ui/src/app/ng2/services/user.service.ts index 87e90432dc..f4186a1087 100644 --- a/catalog-ui/src/app/ng2/services/user.service.ts +++ b/catalog-ui/src/app/ng2/services/user.service.ts @@ -19,80 +19,34 @@ */ import { Injectable, Inject } from "@angular/core"; -import { Headers } from "@angular/http"; import { Observable } from "rxjs/Observable"; -import { HttpService } from "./http.service"; -import { Cookie2Service } from "./cookie.service"; import { IUserProperties } from "../../models/user"; -import {ICookie} from "../../models/app-config"; import {SdcConfigToken, ISdcConfig} from "../config/sdc-config.config"; - +import { HttpClient } from "@angular/common/http"; +import { HttpHelperService } from "./http-hepler.service"; +/** + * User Service provides CRUD for Users. See authentication service for authentication/login. + */ @Injectable() -export class UserService { +export class UserService { private url:string; - private authorizeUrl:string; - private _loggedinUser:IUserProperties; - - constructor(private httpService:HttpService, - private cookieService:Cookie2Service, + constructor(private http: HttpClient, @Inject(SdcConfigToken) private sdcConfig:ISdcConfig) { this.url = this.sdcConfig.api.root + this.sdcConfig.api.GET_user; - this.authorizeUrl = this.sdcConfig.api.root + this.sdcConfig.api.GET_user_authorize; } - public authorize() :Observable { - let cookie:ICookie = this.sdcConfig.cookie; - let authorizeHeaders:Headers = new Headers(); - authorizeHeaders.set(cookie.userFirstName, this.cookieService.getFirstName()); - authorizeHeaders.set(cookie.userLastName, this.cookieService.getLastName()); - authorizeHeaders.set(cookie.userEmail, this.cookieService.getEmail()); - authorizeHeaders.set(cookie.userIdSuffix, this.cookieService.getUserId()); - - return this.httpService.get( - this.authorizeUrl, - { headers: authorizeHeaders } - ).map(resp => resp.json()); - } public getAllUsers() :Observable { - return this.httpService.get( + return this.http.get( this.sdcConfig.api.root + this.sdcConfig.api.GET_all_users - ).map(resp => resp.json()); + ).map(resp => resp) ; } public getUser(userId:string) :Observable { - return this.httpService.get( - HttpService.replaceUrlParams(this.url, { id: userId }) - ).map(resp => resp.json()); - } - - public createUser(userData:{[index:string]: any}) :Observable { - return this.httpService.post( - this.sdcConfig.api.root + this.sdcConfig.api.POST_create_user, - userData - ).map(resp => resp.json()); + return this.http.get( + HttpHelperService.replaceUrlParams(this.url, { id: userId }) + ).map(resp => resp); } - - public deleteUser(userId:string) :Observable { - return this.httpService.delete( - HttpService.replaceUrlParams(this.sdcConfig.api.root + this.sdcConfig.api.DELETE_delete_user, { id: userId }) - ).map(resp => resp.json()); - } - - public editUserRole(userId:string, role:string) :Observable { - return this.httpService.post( - HttpService.replaceUrlParams(this.sdcConfig.api.root + this.sdcConfig.api.POST_edit_user_role, { id: userId }), - { role: role } - ).map(resp => resp.json()); - } - - public getLoggedinUser():IUserProperties { - return this._loggedinUser; - } - - public setLoggedinUser(loggedinUser:IUserProperties) { - this._loggedinUser = loggedinUser; - }; } diff --git a/catalog-ui/src/app/ng2/services/workflow.service.ts b/catalog-ui/src/app/ng2/services/workflow.service.ts index 81a2ea3b7f..044ca37266 100644 --- a/catalog-ui/src/app/ng2/services/workflow.service.ts +++ b/catalog-ui/src/app/ng2/services/workflow.service.ts @@ -1,14 +1,13 @@ import { Injectable, Inject } from "@angular/core"; -import { Response } from "@angular/http"; import { Observable } from "rxjs/Observable"; -import { HttpService } from "./http.service"; import { SdcConfigToken, ISdcConfig } from "../config/sdc-config.config"; +import { HttpClient } from "@angular/common/http"; import { Component, OperationModel } from "app/models"; interface WorkflowOutputParameter { - name: string, - type: string, - mandatory: boolean + name: string; + type: string; + mandatory: boolean; } interface WorkflowInputParameter extends WorkflowOutputParameter { @@ -25,40 +24,31 @@ export class WorkflowServiceNg2 { WF_STATE_ARCHIVED = 'ARCHIVED'; VERSION_STATE_CERTIFIED = 'CERTIFIED'; - constructor(private http: HttpService, @Inject(SdcConfigToken) sdcConfig: ISdcConfig) { + constructor(private http: HttpClient, @Inject(SdcConfigToken) sdcConfig:ISdcConfig) { this.baseUrl = sdcConfig.api.workflow_root; this.catalogBaseUrl = sdcConfig.api.POST_workflow_artifact; } public associateWorkflowArtifact(component: Component, operation: OperationModel): Observable { - return this.http.post(this.baseUrl + '/workflows/' + operation.workflowId + '/versions/' + operation.workflowVersionId + '/artifact-deliveries', { - endpoint: this.catalogBaseUrl + '/' + component.getTypeUrl() + component.uuid + '/interfaces/' + operation.interfaceId + '/operations/' + operation.uniqueId + '/artifacts/' + operation.implementation.artifactUUID, - method: 'POST' - }) - .map((res:Response) => { - return res.json(); + return this.http.post(this.baseUrl + '/workflows/' + operation.workflowId + '/versions/' + operation.workflowVersionId + '/artifact-deliveries', { + endpoint: this.catalogBaseUrl + '/' + component.getTypeUrl() + component.uuid + '/interfaces/' + operation.interfaceId + '/operations/' + + operation.uniqueId + '/artifacts/' + operation.implementation.artifactUUID, method: 'POST' }); } public getWorkflows(filterCertified: boolean = true): Observable { - return this.http.get(this.baseUrl + '/workflows' + (filterCertified ? '?versionState=' + this.VERSION_STATE_CERTIFIED : '')) - .map((res:Response) => { - return res.json().items; - }); + return this.http.get(this.baseUrl + '/workflows' + (filterCertified ? '?versionState=' + this.VERSION_STATE_CERTIFIED : '')); } public getWorkflowVersions(workflowId: string, filterCertified: boolean = true): Observable { - return this.http.get(this.baseUrl + '/workflows/' + workflowId + '/versions' + (filterCertified ? '?state=' + this.VERSION_STATE_CERTIFIED : '')) - .map((res:Response) => { - return _.map(res.json().items, version => version); + return this.http.get(this.baseUrl + '/workflows/' + workflowId + '/versions' + (filterCertified ? '?state=' + this.VERSION_STATE_CERTIFIED : '')) + .map((res) => { + return res.items; }); } public updateWorkflowVersion(workflowId: string, versionId: string, payload: any): Observable { - return this.http.put(this.baseUrl + '/workflows/' + workflowId + '/versions/' + versionId, payload) - .map((res:Response) => { - return res.json(); - }); + return this.http.put(this.baseUrl + '/workflows/' + workflowId + '/versions/' + versionId, payload); } } diff --git a/catalog-ui/src/app/ng2/shared/multiline-ellipsis/multiline-ellipsis.component.html b/catalog-ui/src/app/ng2/shared/multiline-ellipsis/multiline-ellipsis.component.html index bee493f2ae..7b9a5ff700 100644 --- a/catalog-ui/src/app/ng2/shared/multiline-ellipsis/multiline-ellipsis.component.html +++ b/catalog-ui/src/app/ng2/shared/multiline-ellipsis/multiline-ellipsis.component.html @@ -13,7 +13,6 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> -
diff --git a/catalog-ui/src/app/ng2/shared/multiline-ellipsis/multiline-ellipsis.component.ts b/catalog-ui/src/app/ng2/shared/multiline-ellipsis/multiline-ellipsis.component.ts index 68cfedb32b..4cff9de72a 100644 --- a/catalog-ui/src/app/ng2/shared/multiline-ellipsis/multiline-ellipsis.component.ts +++ b/catalog-ui/src/app/ng2/shared/multiline-ellipsis/multiline-ellipsis.component.ts @@ -1,4 +1,4 @@ -import {Component, OnChanges, AfterViewChecked, ViewChild, ElementRef, Input, Output, SimpleChanges, EventEmitter} from "@angular/core"; +import {Component, OnChanges, AfterContentInit, ViewChild, ElementRef, Input, Output, SimpleChanges, EventEmitter} from "@angular/core"; import {WindowRef} from "../../services/window.service"; @Component({ @@ -6,7 +6,7 @@ import {WindowRef} from "../../services/window.service"; templateUrl: 'multiline-ellipsis.component.html', styleUrls: ['multiline-ellipsis.component.less'] }) -export class MultilineEllipsisComponent implements OnChanges, AfterViewChecked { +export class MultilineEllipsisComponent implements OnChanges, AfterContentInit { @Input() public lines: number; @Input() public lineHeight: string; @@ -30,7 +30,7 @@ export class MultilineEllipsisComponent implements OnChanges, AfterViewChecked { this.prepareStyles() } - public ngAfterViewChecked() { + public ngAfterContentInit() { const hasEllipsis = (this.elmContainer.nativeElement.offsetHeight < this.elmContent.nativeElement.offsetHeight); if (hasEllipsis !== this.hasEllipsis) { this.hasEllipsis = hasEllipsis; diff --git a/catalog-ui/src/app/ng2/shared/translator/translate.pipe.ts b/catalog-ui/src/app/ng2/shared/translator/translate.pipe.ts index 4ec756bcc2..04f6650f38 100644 --- a/catalog-ui/src/app/ng2/shared/translator/translate.pipe.ts +++ b/catalog-ui/src/app/ng2/shared/translator/translate.pipe.ts @@ -19,38 +19,32 @@ */ import { Pipe, PipeTransform } from '@angular/core'; -import { TranslateService, ITranslateArgs } from "./translate.service"; +import { ITranslateArgs, TranslateService } from './translate.service'; +// tslint:disable-next-line:interface-name +interface ITranslateParams { + phrase: string; + args: ITranslateArgs; + language: string; +} @Pipe({ name: 'translate', pure: false }) export class TranslatePipe implements PipeTransform { - private translated:string; - private lastParams: { - phrase: string; - args: {[index: string]: any}; - language: string; - } = { + private translated: string; + private lastParams: ITranslateParams = { phrase: undefined, args: undefined, language: undefined }; - constructor(private translateService:TranslateService) { - } - - private shouldUpdate(curParams:{[index:string]: any}) : boolean { - return ( - curParams.language !== this.lastParams.language || - curParams.args !== this.lastParams.args || - curParams.phrase !== this.lastParams.phrase - ); + constructor(private translateService: TranslateService) { } - public transform(phrase:string, args:ITranslateArgs, language:string=this.translateService.activeLanguage) : string { - const curParams = { phrase, args, language }; + public transform(phrase: string, args: ITranslateArgs, language: string = this.translateService.activeLanguage): string { + const curParams: ITranslateParams = { phrase, args, language }; if (this.shouldUpdate(curParams)) { this.lastParams = curParams; this.translated = this.translateService.translate(phrase, args, language); @@ -58,4 +52,12 @@ export class TranslatePipe implements PipeTransform { return this.translated; } + + private shouldUpdate(curParams: ITranslateParams): boolean { + return ( + curParams.language !== this.lastParams.language || + curParams.args !== this.lastParams.args || + curParams.phrase !== this.lastParams.phrase + ); + } } diff --git a/catalog-ui/src/app/ng2/shared/translator/translate.service.config.ts b/catalog-ui/src/app/ng2/shared/translator/translate.service.config.ts index a1d7833062..6413f6a64e 100644 --- a/catalog-ui/src/app/ng2/shared/translator/translate.service.config.ts +++ b/catalog-ui/src/app/ng2/shared/translator/translate.service.config.ts @@ -18,9 +18,9 @@ * ============LICENSE_END========================================================= */ -import { OpaqueToken } from "@angular/core"; +import { InjectionToken } from "@angular/core"; -export const TranslateServiceConfigToken = new OpaqueToken('TranslateServiceConfigToken'); +export const TranslateServiceConfigToken = new InjectionToken('TranslateServiceConfigToken'); export interface ITranslateServiceConfig { filePrefix:string; diff --git a/catalog-ui/src/app/ng2/shared/translator/translate.service.ts b/catalog-ui/src/app/ng2/shared/translator/translate.service.ts index ff7c643b46..0b5ddae557 100644 --- a/catalog-ui/src/app/ng2/shared/translator/translate.service.ts +++ b/catalog-ui/src/app/ng2/shared/translator/translate.service.ts @@ -19,9 +19,9 @@ */ import { Injectable, Inject } from "@angular/core"; -import { Response, Http } from "@angular/http"; -import { Observable, Observer, ConnectableObservable, Subscription } from "rxjs"; import { ITranslateServiceConfig, TranslateServiceConfigToken } from "./translate.service.config"; +import { Observer, Subscription, Observable, ConnectableObservable } from 'rxjs/Rx'; +import { HttpClient } from "@angular/common/http"; export { ITranslateServiceConfig, TranslateServiceConfigToken }; @@ -145,7 +145,7 @@ export class TranslateService { private _cacheLanguagesJsons:{[index:string]:ITranslateLanguageJson} = {}; private _cacheLanguagesLoaders:{[index:string]:Observable} = {}; - constructor(@Inject(TranslateServiceConfigToken) private config:ITranslateServiceConfig, private http:Http) { + constructor(@Inject(TranslateServiceConfigToken) private config:ITranslateServiceConfig, private http: HttpClient) { this.initLanguageObservable(); this.loadAndActivateLanguage(this.config.defaultLanguage); } @@ -176,8 +176,7 @@ export class TranslateService { if (!(language in this._cacheLanguagesLoaders)) { const filePath = `${this.config.filePrefix}${language}${this.config.fileSuffix}`; - this._cacheLanguagesLoaders[language] = this.http.get(filePath) - .map(resp => resp.json()) + this._cacheLanguagesLoaders[language] = this.http.get(filePath) .catch(() => Observable.throw(`Failed to load language file for "${language}"`)) .publish(); (>this._cacheLanguagesLoaders[language]).connect(); @@ -204,12 +203,12 @@ export class TranslateService { return false; } - public loadAndActivateLanguage(language:string) : Observable { + public loadAndActivateLanguage(language:string) : void { + const loadLanguageObservable = this.loadLanguageJsonFile(language, false); loadLanguageObservable.subscribe(() => { this.activateLanguage(language); }, () => {}); - return loadLanguageObservable; } public translate(phraseKey:string, args:ITranslateArgs={}, language:string=this._activeLanguage) : string { diff --git a/catalog-ui/src/app/ng2/store/actions/artifacts.action.ts b/catalog-ui/src/app/ng2/store/actions/artifacts.action.ts new file mode 100644 index 0000000000..a00cc3a9ec --- /dev/null +++ b/catalog-ui/src/app/ng2/store/actions/artifacts.action.ts @@ -0,0 +1,25 @@ +/** + * Created by ob0695 + */ +import {ArtifactModel} from "../../../models/artifacts"; + +export class GetArtifactsByTypeAction { + static readonly type = '[ARTIFACTS] GetArtifactsByType'; + + constructor(public payload: {componentType:string, componentId:string, artifactType: string}) { + } +} + +export class CreateOrUpdateArtifactAction { + static readonly type = '[ARTIFACTS] CreateOrUpdateArtifactAction'; + + constructor(public payload: {componentType:string, componentId:string, artifact:ArtifactModel}) { + } +} + +export class DeleteArtifactAction { + static readonly type = '[ARTIFACTS] DeleteArtifactAction'; + + constructor(public payload: {componentType:string, componentId:string, artifact: ArtifactModel}) { + } +} diff --git a/catalog-ui/src/app/ng2/store/actions/instance-artifacts.actions.ts b/catalog-ui/src/app/ng2/store/actions/instance-artifacts.actions.ts new file mode 100644 index 0000000000..0f1df78352 --- /dev/null +++ b/catalog-ui/src/app/ng2/store/actions/instance-artifacts.actions.ts @@ -0,0 +1,32 @@ +/** + * Created by ob0695 + */ +import {ArtifactModel} from "../../../models/artifacts"; + +export class GetInstanceArtifactsByTypeAction { + static readonly type = '[INSTANCE_ARTIFACTS] GetInstanceArtifactsByTypeAction'; + + constructor(public payload: { componentType: string, componentId: string, artifactType: string, instanceId: string }) { + } +} + +export class CreateInstanceArtifactAction { + static readonly type = '[INSTANCE_ARTIFACTS] CreateInstanceArtifactAction'; + + constructor(public payload: { componentType: string, componentId: string, instanceId: string, artifact: ArtifactModel }) { + } +} + +export class UpdateInstanceArtifactAction { + static readonly type = '[INSTANCE_ARTIFACTS] UpdateInstanceArtifactAction'; + + constructor(public payload: { componentType: string, componentId: string, instanceId: string, artifact: ArtifactModel }) { + } +} + +export class DeleteInstanceArtifactAction { + static readonly type = '[INSTANCE_ARTIFACTS] DeleteInstanceArtifactAction'; + + constructor(public payload: { componentType: string, componentId: string, instanceId: string, artifact: ArtifactModel }) { + } +} diff --git a/catalog-ui/src/app/ng2/store/actions/workspace.action.ts b/catalog-ui/src/app/ng2/store/actions/workspace.action.ts new file mode 100644 index 0000000000..c7f18e0ac6 --- /dev/null +++ b/catalog-ui/src/app/ng2/store/actions/workspace.action.ts @@ -0,0 +1,17 @@ +/** + * Created by ob0695 on 7/17/2018. + */ + +export class UpdateIsViewOnly { + static readonly type = '[WORKSPACE] UpdateIsViewOnly'; + + constructor(public isViewOnly:boolean) { + } +} + +export class UpdateIsDesigner { + static readonly type = '[WORKSPACE] UpdateIsDesigner'; + + constructor(public isDesigner:boolean) { + } +} diff --git a/catalog-ui/src/app/ng2/store/states/artifacts.state.spec.ts b/catalog-ui/src/app/ng2/store/states/artifacts.state.spec.ts new file mode 100644 index 0000000000..c59a4455b6 --- /dev/null +++ b/catalog-ui/src/app/ng2/store/states/artifacts.state.spec.ts @@ -0,0 +1,62 @@ +import { Store } from '@ngxs/store'; +import { Observable } from 'rxjs/Rx'; +import { Mock } from 'ts-mockery'; +import { ArtifactModel } from '../../../models/artifacts'; +import { ArtifactGroupType } from '../../../utils/constants'; +import { ComponentInstanceServiceNg2 } from '../../services/component-instance-services/component-instance.service'; +import { GetInstanceArtifactsByTypeAction, UpdateInstanceArtifactAction } from '../actions/instance-artifacts.actions'; +import { InstanceArtifactsState } from './instance-artifacts.state'; + +describe('Test Artifact State', () => { + + const heat1 = Mock.of({ + uniqueId: '1', artifactName: 'heat1', timeout: 0, artifactDisplayName: 'heat1', artifactGroupType: ArtifactGroupType.DEPLOYMENT + }); + + const heat1env = Mock.of({ + uniqueId: '2', artifactName: 'heat1env', timeout: 0, generatedFromId: '1', artifactDisplayName: 'heat1env', artifactGroupType: ArtifactGroupType.DEPLOYMENT + }); + + const storeMock = Mock.of( { dispatch : jest.fn() }); + + const artifacts = [ + heat1, + heat1env + ]; + + /** + * NGXS Store state before we run the update + */ + const ngxsState = { + deploymentArtifacts : artifacts + }; + + /** + * The ENV artifact that we wish to update + */ + const updatedArtifact = Mock.of({ + uniqueId: '2', artifactName: 'heat1env', timeout: 33, generatedFromId: '1', artifactDisplayName: 'heat1env-UPDATE', artifactGroupType: ArtifactGroupType.DEPLOYMENT + }); + + const componentInstanceServiceMock: ComponentInstanceServiceNg2 = Mock.of({ + updateInstanceArtifact: jest.fn().mockImplementation(() => Observable.of(updatedArtifact)), + getComponentInstanceArtifactsByGroupType: jest.fn().mockImplementation(() => Observable.of([heat1, updatedArtifact])) + }); + + const actionMock: UpdateInstanceArtifactAction = Mock.of({ + payload: { + componentType: '', + componentId: '', + instanceId: '', + artifact: updatedArtifact + } + }); + + it('Test that HEAT timeout is updated', () => { + const state: InstanceArtifactsState = new InstanceArtifactsState(storeMock, componentInstanceServiceMock); + const context = { getState: jest.fn().mockImplementation(() => ngxsState), patchState: jest.fn(), setState: jest.fn(), dispatch: jest.fn() }; + state.updateArtifact(context, actionMock ).subscribe( (v) => console.log('OK')); + expect(storeMock.dispatch).toBeCalled(); + }); + +}); diff --git a/catalog-ui/src/app/ng2/store/states/artifacts.state.ts b/catalog-ui/src/app/ng2/store/states/artifacts.state.ts new file mode 100644 index 0000000000..64efbe96a9 --- /dev/null +++ b/catalog-ui/src/app/ng2/store/states/artifacts.state.ts @@ -0,0 +1,140 @@ +/** + * Created by ob0695 on 7/17/2018. + */ +import { Action, Selector, State, StateContext } from '@ngxs/store'; +import * as _ from 'lodash'; +import { tap } from 'rxjs/operators'; +import { ArtifactModel } from '../../../models/artifacts'; +import { ArtifactGroupType } from '../../../utils/constants'; +import { TopologyTemplateService } from '../../services/component-services/topology-template.service'; +import { ComponentGenericResponse } from '../../services/responses/component-generic-response'; +import { ServiceGenericResponse } from '../../services/responses/service-generic-response'; +import { CreateOrUpdateArtifactAction, DeleteArtifactAction, GetArtifactsByTypeAction } from '../actions/artifacts.action'; + +export interface ArtifactsStateModel { + artifacts: ArtifactModel[]; + deploymentArtifacts: ArtifactModel[]; + toscaArtifacts: ArtifactModel[]; + serviceApiArtifacts: ArtifactModel[]; +} + +@State({ + name: 'artifacts', + defaults: { + artifacts: [], + deploymentArtifacts: [], + toscaArtifacts: [], + serviceApiArtifacts: [] + } +}) + +export class ArtifactsState { + + constructor(protected topologyTemplateService: TopologyTemplateService) { + } + + @Selector() + static getEnvArtifact(state: ArtifactsStateModel, heatEnvArtifact: ArtifactModel) { + return (heatEnvArtifact: ArtifactModel) => { + _.find(state.deploymentArtifacts, (artifact)=> { + return artifact.generatedFromId === heatEnvArtifact.uniqueId + }) + }; + } + + @Selector() + static getArtifactsByType(state: ArtifactsStateModel, type: string) { + return (type: string) => { + switch (type) { + case ArtifactGroupType.TOSCA: + return state.toscaArtifacts; + case ArtifactGroupType.INFORMATION: + return state.artifacts; + case ArtifactGroupType.DEPLOYMENT: + return state.deploymentArtifacts; + case ArtifactGroupType.SERVICE_API: + return state.serviceApiArtifacts; + } + }; + } + + private updateArtifactState = (artifactsState: ArtifactModel[], artifactToUpdate: ArtifactModel, updatedArtifact: ArtifactModel) => { + if (!artifactToUpdate.uniqueId) { // Create Artifact + return [...artifactsState, updatedArtifact] + } else { // Update Artifact + let artifactToUpdateIndex = _.findIndex(artifactsState, (artifact) => { + return artifact.uniqueId === artifactToUpdate.uniqueId + }) + let artifacts = Array.from(artifactsState); + artifacts[artifactToUpdateIndex] = updatedArtifact; + return [...artifacts]; + } + } + + @Action(GetArtifactsByTypeAction) + getArtifactsByType({getState, patchState}: StateContext, action: GetArtifactsByTypeAction) { + const state = getState(); + return this.topologyTemplateService.getArtifactsByType(action.payload.componentType, action.payload.componentId, action.payload.artifactType) + .pipe(tap((resp: ComponentGenericResponse) => { + switch (action.payload.artifactType) { + case ArtifactGroupType.INFORMATION: + patchState({ + artifacts: _.values(resp.artifacts) + }); + + case ArtifactGroupType.DEPLOYMENT: + patchState({ + deploymentArtifacts: _.values(resp.deploymentArtifacts) + }); + + case ArtifactGroupType.TOSCA: + patchState({ + toscaArtifacts: _.values(resp.toscaArtifacts) + }); + + case ArtifactGroupType.SERVICE_API: + patchState({ + serviceApiArtifacts: _.values((resp).serviceApiArtifacts) + }); + } + })); + } + + @Action(CreateOrUpdateArtifactAction) + createOrUpdateArtifact({getState, patchState}: StateContext, action: CreateOrUpdateArtifactAction) { + const state = getState(); + return this.topologyTemplateService.addOrUpdateArtifact(action.payload.componentType, action.payload.componentId, action.payload.artifact) + .pipe(tap((resp: ArtifactModel) => { + + switch (resp.artifactGroupType) { + case ArtifactGroupType.DEPLOYMENT: + patchState({ + deploymentArtifacts: this.updateArtifactState(state.deploymentArtifacts, action.payload.artifact, resp) + }); + + case ArtifactGroupType.INFORMATION: + patchState({ + artifacts: this.updateArtifactState(state.artifacts, action.payload.artifact, resp) + }); + } + })); + } + + @Action(DeleteArtifactAction) + deleteArtifact({getState, patchState}: StateContext, action: DeleteArtifactAction) { + const state = getState(); + return this.topologyTemplateService.deleteArtifact(action.payload.componentId, action.payload.componentType, action.payload.artifact.uniqueId, action.payload.artifact.artifactLabel) + .pipe(tap((resp: ArtifactModel) => { + switch (resp.artifactGroupType) { + case ArtifactGroupType.DEPLOYMENT: + patchState({ + deploymentArtifacts: state.deploymentArtifacts.filter(({uniqueId}) => uniqueId !== action.payload.artifact.uniqueId) + }); + case ArtifactGroupType.INFORMATION: + patchState({ + artifacts: state.artifacts.filter(({uniqueId}) => uniqueId !== action.payload.artifact.uniqueId) + }); + } + })); + } +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/store/states/instance-artifacts.state.ts b/catalog-ui/src/app/ng2/store/states/instance-artifacts.state.ts new file mode 100644 index 0000000000..12ba1ae7ba --- /dev/null +++ b/catalog-ui/src/app/ng2/store/states/instance-artifacts.state.ts @@ -0,0 +1,145 @@ +/** + * Created by ob0695 on 7/17/2018. + */ +import { Action, Selector, State, StateContext, Store } from '@ngxs/store'; +import * as _ from 'lodash'; +import { tap } from 'rxjs/operators'; +import { ArtifactModel } from '../../../models/artifacts'; +import { ArtifactGroupType } from '../../../utils/constants'; +import { ComponentInstanceServiceNg2 } from '../../services/component-instance-services/component-instance.service'; +import { ComponentGenericResponse } from '../../services/responses/component-generic-response'; +import { + CreateInstanceArtifactAction, + DeleteInstanceArtifactAction, + GetInstanceArtifactsByTypeAction, + UpdateInstanceArtifactAction +} from '../actions/instance-artifacts.actions'; +import { ArtifactsStateModel } from './artifacts.state'; + +export interface InstanceArtifactsStateModel { + artifacts: ArtifactModel[]; + deploymentArtifacts: ArtifactModel[]; +} + +@State({ + name: 'instance_artifacts', + defaults: { + artifacts: [], + deploymentArtifacts: [] + } +}) +export class InstanceArtifactsState { + + constructor(private store: Store, protected componentInstanceService: ComponentInstanceServiceNg2) { + } + + @Selector() + static getArtifactsByType(state: InstanceArtifactsStateModel) { + return (type: string) => { + switch (type) { + case ArtifactGroupType.INFORMATION: + return state.artifacts; + case ArtifactGroupType.DEPLOYMENT: + return state.deploymentArtifacts; + } + }; + } + + @Action(GetInstanceArtifactsByTypeAction) + getInstanceArtifactsByType({getState, patchState}: StateContext, action: GetInstanceArtifactsByTypeAction) { + const state = getState(); + return this.componentInstanceService.getComponentInstanceArtifactsByGroupType(action.payload.componentType, action.payload.componentId, action.payload.instanceId, action.payload.artifactType) + .pipe(tap((resp: ComponentGenericResponse) => { + switch (action.payload.artifactType) { + case ArtifactGroupType.INFORMATION: + patchState({ + artifacts: _.values(resp) as ArtifactModel[] + }); + break; + case ArtifactGroupType.DEPLOYMENT: + patchState({ + deploymentArtifacts: _.values(resp) as ArtifactModel[] + }); + break; + } + })); + } + + @Action(CreateInstanceArtifactAction) + createArtifact({getState, patchState}: StateContext, action: CreateInstanceArtifactAction) { + const state = getState(); + return this.componentInstanceService.addInstanceArtifact(action.payload.componentType, action.payload.componentId, action.payload.instanceId, action.payload.artifact) + .pipe(tap((resp: ArtifactModel) => { + switch (resp.artifactGroupType) { + case ArtifactGroupType.DEPLOYMENT: + patchState({ + deploymentArtifacts: [...state.deploymentArtifacts, resp] + }); + break; + case ArtifactGroupType.INFORMATION: + patchState({ + artifacts: [...state.artifacts, resp] + }); + break; + } + })); + } + + @Action(UpdateInstanceArtifactAction) + updateArtifact({getState, patchState}: StateContext, action: UpdateInstanceArtifactAction) { + const state = getState(); + return this.componentInstanceService.updateInstanceArtifact(action.payload.componentType, action.payload.componentId, action.payload.instanceId, action.payload.artifact) + .pipe(tap((resp: ArtifactModel) => { + switch (resp.artifactGroupType) { + case ArtifactGroupType.DEPLOYMENT: + // We cannot simply update the updated artifact state because updating a deployment ENV file may cause an update to his parent HEAT + // file. + // Just dispatch an action to refresh the deployment artifacts list + this.store.dispatch(new GetInstanceArtifactsByTypeAction(({ + componentType: action.payload.componentType, + componentId: action.payload.componentId, + instanceId: action.payload.instanceId, + artifactType: ArtifactGroupType.DEPLOYMENT + }))); + break; + case ArtifactGroupType.INFORMATION: + patchState({ + artifacts: this.updateInstanceArtifactState(state.artifacts, action.payload.artifact, resp) + }); + break; + } + })); + } + + @Action(DeleteInstanceArtifactAction) + deleteInstanceArtifact({getState, patchState}: StateContext, action: DeleteInstanceArtifactAction) { + const state = getState(); + return this.componentInstanceService. + deleteInstanceArtifact(action.payload.componentId, action.payload.componentType, action.payload.instanceId, action.payload.artifact.uniqueId, action.payload.artifact.artifactLabel) + .pipe(tap((resp: ArtifactModel) => { + switch (resp.artifactGroupType) { + case ArtifactGroupType.DEPLOYMENT: + patchState({ + deploymentArtifacts: state.deploymentArtifacts.filter(({uniqueId}) => uniqueId !== action.payload.artifact.uniqueId) + }); + break; + case ArtifactGroupType.INFORMATION: + patchState({ + artifacts: state.artifacts.filter(({uniqueId}) => uniqueId !== action.payload.artifact.uniqueId) + }); + break; + } + })); + } + + private updateInstanceArtifactState = (artifactsState: ArtifactModel[], artifactToUpdate: ArtifactModel, updatedArtifact: ArtifactModel) => { + const artifactToUpdateIndex = _.findIndex(artifactsState, (artifact) => { + return artifact.uniqueId === artifactToUpdate.uniqueId; + }); + const artifacts = Array.from(artifactsState); + artifacts[artifactToUpdateIndex] = updatedArtifact; + const ret = [...artifacts]; + return ret; + } + +} diff --git a/catalog-ui/src/app/ng2/store/states/workspace.state.ts b/catalog-ui/src/app/ng2/store/states/workspace.state.ts new file mode 100644 index 0000000000..eb8200f6e0 --- /dev/null +++ b/catalog-ui/src/app/ng2/store/states/workspace.state.ts @@ -0,0 +1,48 @@ +/** + * Created by ob0695 on 7/17/2018. + */ +import {State, Action, StateContext} from '@ngxs/store'; +import {UpdateIsDesigner, UpdateIsViewOnly} from "../actions/workspace.action"; +import {Selector} from "@ngxs/store"; + +export interface WorkspaceStateModel { + isViewOnly: boolean; + isDesigner: boolean; +} + +@State({ + name: 'workspace', + defaults: { + isViewOnly: false, + isDesigner: true + } +}) + +export class WorkspaceState { + + constructor(){} + + @Selector() static isViewOnly(state: WorkspaceStateModel):boolean { + return state.isViewOnly; + } + @Selector() static isDesigner(state: WorkspaceStateModel): boolean { + return state.isDesigner; + } + + @Action(UpdateIsViewOnly) + updateIsViewOnly({getState, setState}: StateContext, action:UpdateIsViewOnly) { + const state = getState(); + setState({ + ...state, + isViewOnly: action.isViewOnly + }); + } + + @Action(UpdateIsDesigner) + updateIsDesigner({getState, patchState}: StateContext, action:UpdateIsDesigner) { + const state = getState(); + patchState({ + isDesigner: action.isDesigner + }); + } +} \ No newline at end of file diff --git a/catalog-ui/src/app/ng2/utils/ng1-upgraded-provider.ts b/catalog-ui/src/app/ng2/utils/ng1-upgraded-provider.ts index fcb21c0c83..aab531d205 100644 --- a/catalog-ui/src/app/ng2/utils/ng1-upgraded-provider.ts +++ b/catalog-ui/src/app/ng2/utils/ng1-upgraded-provider.ts @@ -23,13 +23,12 @@ */ import { DataTypesService } from "../../services/data-types-service"; import ICacheObject = angular.ICacheObject; -import { SharingService } from "../../services/sharing-service"; import { CookieService } from "../../services/cookie-service"; -import { CacheService } from "../../services/cache-service"; import {ComponentFactory} from "../../utils/component-factory" import { EventListenerService } from "app/services/event-listener-service"; import { ModalsHandler } from "app/utils"; import IScope = angular.IScope; +import { SharingService } from "../services/sharing.service"; /** Services we need to upgrade from angular1 to angular2 - in the future we need to rewrite them all to angular2 **/ @@ -61,10 +60,6 @@ export function scopeServiceFactory(cacheObj: ICacheObject) { return cacheObj.get('$scope'); } -export function cacheServiceFactory(cacheObj: ICacheObject) { - return cacheObj.get('Sdc.Services.CacheService'); -} - export function eventListenerServiceServiceFactory(cacheObj: ICacheObject) { return cacheObj.get('EventListenerService'); } @@ -73,6 +68,10 @@ export function notificationServiceFactory(cacheObj: ICacheObject) { return cacheObj.get('Notification'); } +export function ModalsHandlerFactory(cacheObj: ICacheObject) { + return cacheObj.get('ModalsHandler'); +} + export const ComponentFactoryProvider = { provide: ComponentFactory, @@ -80,18 +79,12 @@ export const ComponentFactoryProvider = { deps: ['$injector'] }; - -export function ModalsHandlerFactory(cacheObj: ICacheObject) { - return cacheObj.get('ModalsHandler'); -} - export const DataTypesServiceProvider = { provide: DataTypesService, useFactory: dataTypesServiceFactory, deps: ['$injector'] }; - export const SharingServiceProvider = { provide: SharingService, useFactory: sharingServiceFactory, @@ -122,17 +115,12 @@ export const StateParamsServiceFactory = { useFactory: stateParamsServiceFactory, deps: ['$injector'] }; -export const CacheServiceProvider = { - provide: CacheService, - useFactory: cacheServiceFactory, - deps: ['$injector'] -}; - -export const EventListenerServiceProvider = { - provide: EventListenerService, - useFactory: eventListenerServiceServiceFactory, - deps: ['$injector'] -}; +// +// export const EventListenerServiceProvider = { +// provide: EventListenerService, +// useFactory: eventListenerServiceServiceFactory, +// deps: ['$injector'] +// }; export const NotificationServiceProvider = { provide: 'Notification', @@ -144,4 +132,4 @@ export const ModalsHandlerProvider = { provide: ModalsHandler, useFactory: ModalsHandlerFactory, deps: ['$injector'] -} +}; diff --git a/catalog-ui/src/app/ng2/utils/queue-service-utils.ts b/catalog-ui/src/app/ng2/utils/queue-service-utils.ts new file mode 100644 index 0000000000..8cf7f98383 --- /dev/null +++ b/catalog-ui/src/app/ng2/utils/queue-service-utils.ts @@ -0,0 +1,58 @@ +/** + * Created by ob0695 on 6/3/2018. + */ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +import {Injectable} from "@angular/core"; + +@Injectable() +export class QueueServiceUtils { + + private executionQueue:any; + + constructor() { + if(!this.executionQueue) { + this.executionQueue = this.getQueue(); + } + } + + private getQueue = () => new Promise((resolve, reject) => { + resolve(true); + }); + + private addMethodToQueue = (runMe:Function):void => { + this.executionQueue = this.executionQueue.then(runMe, runMe); + }; + + addNonBlockingUIAction = (update:Function, releaseUIcallBack?:Function):void => { + // releaseUIcallBack(); + this.addMethodToQueue(update); + }; + + // The Method call is responsible for releasing the UI + addBlockingUIAction = (blockingServerRequest:Function):void => { + this.addMethodToQueue(blockingServerRequest); + }; + + addBlockingUIActionWithReleaseCallback = (blockingServerRequest:Function, releaseUIcallBack:Function):void=> { + this.addMethodToQueue(blockingServerRequest); + // this.addMethodToQueue(releaseUIcallBack); + }; +} diff --git a/catalog-ui/src/app/services-ng2.ts b/catalog-ui/src/app/services-ng2.ts new file mode 100644 index 0000000000..e2811ba68d --- /dev/null +++ b/catalog-ui/src/app/services-ng2.ts @@ -0,0 +1,27 @@ +// Angular 2 services +export * from './ng2/services/config.service'; +export * from './ng2/services/authentication.service'; +export * from './ng2/services/user.service'; +export * from './ng2/services/data-type.service'; +export * from './ng2/services/modal.service'; +export * from './ng2/services/plugins.service'; +export * from './ng2/services/sharing.service'; +export * from './ng2/services/cache.service'; +export * from './ng2/services/cookie.service'; +export * from './ng2/services/home.service'; +export * from './ng2/services/catalog.service'; +export * from './ng2/services/policies.service'; +export * from './ng2/services/properties.service'; +export * from './ng2/services/window.service'; +export * from './ng2/services/dynamic-component.service'; +export * from './ng2/services/event-bus.service'; +export * from './ng2/services/groups.service'; + +export * from './ng2/services/component-services/component.service'; +export * from './ng2/services/component-services/component.service.factory'; +export * from './ng2/services/component-services/service.service'; +export * from './ng2/services/component-services/resource.service'; +export * from './ng2/services/component-services/component-mode.service'; + +export * from './ng2/services/onboarding.service'; +export * from './ng2/components/modals/onboarding-modal/import-vsp.service' diff --git a/catalog-ui/src/app/services.ts b/catalog-ui/src/app/services.ts index 79b5132634..be77fed951 100644 --- a/catalog-ui/src/app/services.ts +++ b/catalog-ui/src/app/services.ts @@ -21,9 +21,7 @@ /** * Created by ob0695 on 2/23/2017. */ -export * from './services/activity-log-service'; export * from './services/available-icons-service'; -export * from './services/cache-service'; export * from './services/configuration-ui-service'; export * from './services/category-resource-service'; export * from './services/components/component-service'; @@ -37,14 +35,10 @@ export * from './services/category-resource-service'; export * from './services/cookie-service'; export * from './services/data-types-service'; export * from './services/ecomp-service'; -export * from './services/entity-service'; export * from './services/event-listener-service'; export * from './services/header-interceptor'; export * from './services/loader-service'; -export * from './services/onboarding-service'; export * from './services/progress-service'; export * from './services/sdc-version-service'; -export * from './services/sharing-service'; export * from './services/url-tobase64-service'; export * from './services/angular-js-bridge-service'; - diff --git a/catalog-ui/src/app/services/activity-log-service.ts b/catalog-ui/src/app/services/activity-log-service.ts deleted file mode 100644 index 97d26d4f44..0000000000 --- a/catalog-ui/src/app/services/activity-log-service.ts +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {Activity} from "../models/activity"; -import {IAppConfigurtaion, IApi} from "../models/app-config"; - -// Define an interface of the object you want to use, providing it's properties -export interface IActivityLogService { - getActivityLogService(type:string, id:string):ng.IPromise>; -} - -export class ActivityLogService implements IActivityLogService { - - - static '$inject' = ['$http', '$q', 'sdcConfig']; - private api:IApi; - - constructor(private $http:ng.IHttpService, private $q:ng.IQService, sdcConfig:IAppConfigurtaion) { - this.api = sdcConfig.api; - } - - getActivityLogService = (type:string, id:string):ng.IPromise> => { - let defer = this.$q.defer(); - this.$http.get(this.api.root + this.api.GET_activity_log.replace(':type', type).replace(':id', id)) - .then((activityLog:any) => { - defer.resolve(activityLog.data); - }); - return defer.promise; - } -} diff --git a/catalog-ui/src/app/services/cache-service.ts b/catalog-ui/src/app/services/cache-service.ts deleted file mode 100644 index 4d10db0066..0000000000 --- a/catalog-ui/src/app/services/cache-service.ts +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {Dictionary} from "app/utils"; - -interface ICacheService { - get(key:string):any; - set(key:string, value:any):void; -} - -export class CacheService implements ICacheService { - - private storage:Dictionary; - - constructor() { - this.storage = new Dictionary(); - }; - - public get = (key:string):any => { - return this.storage.getValue(key); - }; - - public set = (key:string, value:any):void => { - this.storage.setValue(key, value); - }; - - public remove = (key:string):void => { - if (this.storage.containsKey(key)) { - this.storage.remove(key); - } - }; - - public contains = (key:string):boolean => { - return this.storage.containsKey(key); - }; -} diff --git a/catalog-ui/src/app/services/components/component-service.ts b/catalog-ui/src/app/services/components/component-service.ts index 25203e7732..c7ab975e6e 100644 --- a/catalog-ui/src/app/services/components/component-service.ts +++ b/catalog-ui/src/app/services/components/component-service.ts @@ -22,7 +22,7 @@ import * as _ from "lodash"; import {ArtifactModel, IFileDownload, InstancesInputsPropertiesMap, InputModel, IValidate, RelationshipModel, PropertyModel, Component, ComponentInstance, AttributeModel, IAppConfigurtaion, Resource, Module, DisplayModule, ArtifactGroupModel, InputsAndProperties} from "app/models"; import {ComponentInstanceFactory, CommonUtils} from "app/utils"; -import {SharingService} from "../sharing-service"; +import {SharingService} from "app/services-ng2"; import {ComponentMetadata} from "../../models/component-metadata"; export interface IComponentService { @@ -683,7 +683,6 @@ export class ComponentService implements IComponentService { public getComponentInstanceProperties = (componentId:string, instanceId:string):ng.IPromise> => { - let deferred = this.$q.defer>(); this.restangular.one(componentId).one("componentInstances").one(instanceId).one("properties").get().then((response:any) => { console.log("component instance properties return successfully: ", response); diff --git a/catalog-ui/src/app/services/components/resource-service.ts b/catalog-ui/src/app/services/components/resource-service.ts index cb30107a69..3a00da1171 100644 --- a/catalog-ui/src/app/services/components/resource-service.ts +++ b/catalog-ui/src/app/services/components/resource-service.ts @@ -25,7 +25,7 @@ import * as _ from "lodash"; import {IComponentService, ComponentService} from "./component-service"; import {PropertyModel, IAppConfigurtaion, Resource, Component} from "../../models"; -import {SharingService} from "../sharing-service"; +import {SharingService} from "app/services-ng2"; export interface IResourceService extends IComponentService { updateResourceGroupProperties(uniqueId:string, groupId:string, properties:Array):ng.IPromise> diff --git a/catalog-ui/src/app/services/components/service-service.ts b/catalog-ui/src/app/services/components/service-service.ts index f258c7be98..6c318bd6d6 100644 --- a/catalog-ui/src/app/services/components/service-service.ts +++ b/catalog-ui/src/app/services/components/service-service.ts @@ -25,7 +25,7 @@ import * as _ from "lodash"; import {IComponentService, ComponentService} from "./component-service"; import {Distribution, DistributionComponent, Service, PropertyModel, Component, IAppConfigurtaion} from "app/models"; -import {SharingService} from "../sharing-service"; +import {SharingService} from "app/services-ng2"; export interface IServiceService extends IComponentService { getDistributionsList(uuid:string):ng.IPromise>; diff --git a/catalog-ui/src/app/services/components/utils/composition-left-palette-service.ts b/catalog-ui/src/app/services/components/utils/composition-left-palette-service.ts index 99be788547..b47c5e019b 100644 --- a/catalog-ui/src/app/services/components/utils/composition-left-palette-service.ts +++ b/catalog-ui/src/app/services/components/utils/composition-left-palette-service.ts @@ -32,11 +32,13 @@ import {ComponentMetadata} from "app/models/component-metadata"; import {GroupMetadata, GroupTpes} from "app/models/group-metadata"; import {PolicyMetadata, PolicyTpes} from "app/models/policy-metadata"; import {Resource} from "app/models/components/resource"; +import IHttpPromiseCallbackArg = angular.IHttpPromiseCallbackArg; export class LeftPaletteLoaderService { static '$inject' = [ 'Restangular', + '$http', 'sdcConfig', '$q', 'ComponentFactory', @@ -45,6 +47,7 @@ export class LeftPaletteLoaderService { ]; constructor(protected restangular:restangular.IElement, + protected $http:ng.IHttpService, protected sdcConfig:IAppConfigurtaion, protected $q:ng.IQService, protected ComponentFactory:ComponentFactory, @@ -64,7 +67,9 @@ export class LeftPaletteLoaderService { private updateLeftPalette = (componentInternalType:string):void => { /* add components */ - this.restangular.one("resources").one('/latestversion/notabstract/metadata').get({'internalComponentType': componentInternalType}).then((leftPaletteComponentMetadata:Array) => { + const leftPaletteUrl = this.sdcConfig.api.uicache_root + this.sdcConfig.api.GET_uicache_left_palette; + this.$http.get(leftPaletteUrl, {params: {'internalComponentType': componentInternalType}}).then((res) => res.data).then((leftPaletteComponentMetadata:Array) => { + // this.restangular.one("resources").one('/latestversion/notabstract/metadata').get({'internalComponentType': componentInternalType}).then((leftPaletteComponentMetadata:Array) => { _.forEach(leftPaletteComponentMetadata, (componentMetadata:ComponentMetadata) => { this.leftPanelComponents.push(new LeftPaletteComponent(LeftPaletteMetadataTypes.Component, componentMetadata)); }); diff --git a/catalog-ui/src/app/services/entity-service.ts b/catalog-ui/src/app/services/entity-service.ts deleted file mode 100644 index 2e7b2e1eed..0000000000 --- a/catalog-ui/src/app/services/entity-service.ts +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import * as _ from "lodash"; -import { Service, IApi, IAppConfigurtaion, Resource, Component} from "../models"; -import {SharingService} from "./sharing-service"; -import {ComponentFactory} from "../utils/component-factory"; -import {CacheService} from "./cache-service"; -import {ResourceType} from "app/utils"; - -interface IEntityService { - getAllComponents(smallObjects?:boolean):ng.IPromise>; -} - -interface IComponentsArray { - services:Array; - resources:Array; -} - -export class EntityService implements IEntityService { - static '$inject' = ['$http', '$q', 'sdcConfig', 'Sdc.Services.SharingService', 'ComponentFactory', 'Sdc.Services.CacheService']; - private _smallObjectAttributes = ['uniqueId', 'name', 'componentType', 'resourceType', 'lastUpdateDate', 'lifecycleState', 'distributionStatus', 'icon', 'version']; - private api:IApi; - - constructor(private $http:ng.IHttpService, - private $q:ng.IQService, - private sdcConfig:IAppConfigurtaion, - private sharingService:SharingService, - private ComponentFactory:ComponentFactory, - private cacheService:CacheService) { - this.api = sdcConfig.api; - } - - getCatalog = ():ng.IPromise> => { - let defer = this.$q.defer>(); - this.$http.get(this.api.root + this.api.GET_catalog, {params: {excludeTypes: [ResourceType.VFCMT, ResourceType.CONFIGURATION]}}) - .then((response:any) => { - let followedResponse: IComponentsArray = response.data; - let componentsList:Array = new Array(); - - followedResponse.services && followedResponse.services.forEach((serviceResponse:Service) => { - let component:Service = this.ComponentFactory.createService(serviceResponse); // new Service(serviceResponse); - componentsList.push(component); - this.sharingService.addUuidValue(component.uniqueId, component.uuid); - }); - - followedResponse.resources && followedResponse.resources.forEach((resourceResponse:Resource) => { - let component:Resource = this.ComponentFactory.createResource(resourceResponse); - componentsList.push(component); - this.sharingService.addUuidValue(component.uniqueId, component.uuid); - }); - - defer.resolve(componentsList); - },(responce) => { - defer.reject(responce); - }); - return defer.promise; - }; - - getAllComponents = (smallObjects?:boolean):ng.IPromise> => { - let defer = this.$q.defer>(); - this.$http.get(this.api.root + this.api.GET_element) - .then((response:any) => { - let componentResponse:IComponentsArray = response.data; - let componentsList:Array = []; - - componentResponse.services && componentResponse.services.forEach((serviceResponse:Service) => { - serviceResponse = (smallObjects) ? _.pick(serviceResponse, this._smallObjectAttributes) : serviceResponse; - let component:Service = this.ComponentFactory.createService(serviceResponse); - componentsList.push(component); - this.sharingService.addUuidValue(component.uniqueId, component.uuid); - }); - - componentResponse.resources && componentResponse.resources.forEach((resourceResponse:Resource) => { - resourceResponse = (smallObjects) ? _.pick(resourceResponse, this._smallObjectAttributes) : resourceResponse; - let component:Resource = this.ComponentFactory.createResource(resourceResponse); - componentsList.push(component); - this.sharingService.addUuidValue(component.uniqueId, component.uuid); - }); - - defer.resolve(componentsList); - }); - - return defer.promise; - }; -} diff --git a/catalog-ui/src/app/services/event-listener-service.ts b/catalog-ui/src/app/services/event-listener-service.ts index 360edad700..2d3c4a6fc8 100644 --- a/catalog-ui/src/app/services/event-listener-service.ts +++ b/catalog-ui/src/app/services/event-listener-service.ts @@ -23,22 +23,21 @@ 'use strict'; import * as _ from "lodash"; import {Dictionary} from "../utils/dictionary/dictionary"; +import {Injectable} from "@angular/core"; -interface IEventListenerService { - -} interface ICallbackData { - callback:Function; - args:any[]; + callback: Function; + args: any[]; } -export class EventListenerService implements IEventListenerService { +@Injectable() +export class EventListenerService { - public observerCallbacks:Dictionary = new Dictionary>(); + public observerCallbacks: Dictionary = new Dictionary>(); //register an observer + callback - public registerObserverCallback = (eventName:string, callback:Function, ...args) => { + public registerObserverCallback = (eventName: string, callback: Function, ...args) => { let callbackData = { callback: callback, args: args @@ -62,11 +61,11 @@ export class EventListenerService implements IEventListenerService { }; //unregister an observer - public unRegisterObserver = (eventName:string, callbackFunc?:Function) => { + public unRegisterObserver = (eventName: string, callbackFunc?: Function) => { if (this.observerCallbacks.containsKey(eventName)) { - let callbacks: ICallbackData[] = this.observerCallbacks.getValue(eventName); - if(callbacks.length === 1) { + let callbacks: ICallbackData[] = this.observerCallbacks.getValue(eventName); + if (callbacks.length === 1) { this.observerCallbacks.remove(eventName); } else { let filterCallbacks = _.filter(callbacks, (callBackObj) => { @@ -74,13 +73,12 @@ export class EventListenerService implements IEventListenerService { }); this.observerCallbacks.setValue(eventName, filterCallbacks); } - } }; - public notifyObservers = function (eventName:string, ...args) { - _.forEach(this.observerCallbacks.getValue(eventName), (callbackData:ICallbackData) => { - callbackData.callback(...args); - }); + public notifyObservers = function (eventName: string, ...args) { + _.forEach(this.observerCallbacks.getValue(eventName), (callbackData: ICallbackData) => { + callbackData.callback(...args); + }); }; } diff --git a/catalog-ui/src/app/services/header-interceptor.ts b/catalog-ui/src/app/services/header-interceptor.ts index 931b292d60..5f4819ae88 100644 --- a/catalog-ui/src/app/services/header-interceptor.ts +++ b/catalog-ui/src/app/services/header-interceptor.ts @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,17 +19,19 @@ */ 'use strict'; -import {IAppConfigurtaion} from "../models/app-config"; -import {Dictionary} from "../utils/dictionary/dictionary"; -import {SharingService} from "./sharing-service"; - -//Method name should be exactly "response" - http://docs.angularjs.org/api/ng/service/$http -export interface IInterceptor { - request:Function; +import { SharingService } from 'app/services-ng2'; +import { IAppConfigurtaion } from '../models/app-config'; +import { ServerErrorResponse } from '../models/server-error-response'; +import { Dictionary } from '../utils/dictionary/dictionary'; +// Method name should be exactly "response" - http://docs.angularjs.org/api/ng/service/$http +export interface Interceptor { + request: Function; + response: Function; + responseError: Function; } -export class HeaderInterceptor implements IInterceptor { +export class HeaderInterceptor implements Interceptor { public static $inject = [ '$injector', '$q', @@ -39,51 +41,55 @@ export class HeaderInterceptor implements IInterceptor { '$location' ]; - public static Factory($injector:ng.auto.IInjectorService, - $q:ng.IQService, - uuid4:any, - sharingService:SharingService, - sdcConfig:IAppConfigurtaion, - $location:ng.ILocationService) { - return new HeaderInterceptor($injector, $q, uuid4, sharingService, sdcConfig, $location); - } - - constructor(private $injector:ng.auto.IInjectorService, - private $q:ng.IQService, - private uuid4:any, - private sharingService:SharingService, - private sdcConfig:IAppConfigurtaion, - private $location:ng.ILocationService) { - console.debug('header-interceptor: initializing AuthenticationInterceptor'); + constructor(private $injector: ng.auto.IInjectorService, + private $q: ng.IQService, + private uuid4: any, + private sharingService: SharingService, + private sdcConfig: IAppConfigurtaion, + private $location: ng.ILocationService) { } - public request = (requestSuccess):ng.IPromise => { + public request = (requestSuccess): ng.IPromise => { requestSuccess.headers['X-ECOMP-RequestID'] = this.uuid4.generate(); /** * For every request to the server, that the service id, or resource id is sent in the URL, need to pass UUID in the header. * Check if the unique id exists in uuidMap, and if so get the UUID and add it to the header. */ - let map:Dictionary = this.sharingService.getUuidMap(); + const map: Dictionary = this.sharingService.getUuidMap(); if (map && requestSuccess.url.indexOf(this.sdcConfig.api.root) === 0) { - console.log("header-interceptor: url: " + requestSuccess.url); - map.forEach((key:string) => { + map.forEach((key: string) => { if (requestSuccess.url.indexOf(key) !== -1) { requestSuccess.headers['X-ECOMP-ServiceID'] = this.sharingService.getUuidValue(key); } }); } return requestSuccess; - }; + } - public response = (responseSuccess):ng.IPromise => { - let responseData = responseSuccess.data; + public response = (responseSuccess): ng.IPromise => { + const responseData = responseSuccess.data; if (responseData) { - let data = JSON.stringify(responseData); - if (data && (data.indexOf("Global Logon: Login") > 0)) { + const data = JSON.stringify(responseData); + if (data && (data.indexOf('Global Logon: Login') > 0)) { this.$location.path('dashboard/welcome'); window.location.reload(); } } return responseSuccess; } + + public responseError = (response): ng.IPromise => { + const errorResponse: ServerErrorResponse = new ServerErrorResponse(response, true); + const modalService = this.$injector.get('ModalServiceSdcUI'); + + const errorDetails = { + 'Error Code': errorResponse.messageId, + 'Status Code': errorResponse.status + }; + if (errorResponse.ecompRequestId) { + errorDetails['Transaction ID'] = errorResponse.ecompRequestId; + } + modalService.openErrorDetailModal('Error', errorResponse.message, 'error-modal', errorDetails); + return this.$q.reject(errorResponse); + } } diff --git a/catalog-ui/src/app/services/http-error-interceptor.ts b/catalog-ui/src/app/services/http-error-interceptor.ts deleted file mode 100644 index cef8c30716..0000000000 --- a/catalog-ui/src/app/services/http-error-interceptor.ts +++ /dev/null @@ -1,119 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {IServerMessageModalModel} from "../view-models/modals/message-modal/message-server-modal/server-message-modal-view-model"; -import {SEVERITY} from "../utils/constants"; -import 'app/utils/prototypes.ts'; - -export class HttpErrorInterceptor { - public static $inject = ['$injector', '$q']; - - public static Factory($injector:ng.auto.IInjectorService, $q:angular.IQService) { - return new HttpErrorInterceptor($injector, $q); - } - - constructor(private $injector:ng.auto.IInjectorService, private $q:angular.IQService) { - } - - public formatMessageArrays = (message:string, variables:Array)=> { - return message.replace(/\[%(\d+)\]/g, function (_, m) { - let tmp = []; - let list = variables[--m].split(";"); - list.forEach(function (item) { - tmp.push("
  • " + item + "
  • "); - }); - return "
      " + tmp.join("") + "
    "; - }); - }; - - public responseError = (rejection:any)=> { - - let text:string; - let variables; - let messageId:string = ""; - let isKnownException = false; - - if (rejection.data && rejection.data.serviceException) { - text = rejection.data.serviceException.text; - variables = rejection.data.serviceException.variables; - messageId = rejection.data.serviceException.messageId; - isKnownException = true; - } else if (rejection.data && rejection.data.requestError && rejection.data.requestError.serviceException) { - text = rejection.data.requestError.serviceException.text; - variables = rejection.data.requestError.serviceException.variables; - messageId = rejection.data.requestError.serviceException.messageId; - isKnownException = true; - } else if (rejection.data && rejection.data.requestError && rejection.data.requestError.policyException) { - text = rejection.data.requestError.policyException.text; - variables = rejection.data.requestError.policyException.variables; - messageId = rejection.data.requestError.policyException.messageId; - isKnownException = true; - } else if (rejection.data) { - text = 'Wrong error format from server'; - console.error(text); - isKnownException = false; - } - - let data:IServerMessageModalModel; - if (isKnownException) { - // Remove the "Error: " text at the begining - if (text.trim().indexOf("Error:") === 0) { - text = text.replace("Error:", "").trim(); - } - - //mshitrit DE199895 bug fix - let count:number = 0; - variables.forEach(function (item) { - variables[count] = item ? item.replace('<', '<').replace('>', '>') : ''; - count++; - }); - - // Format the message in case has array to
    • - text = this.formatMessageArrays(text, variables); - - // Format the message %1 %2 - text = text.format(variables); - - // Need to inject the MessageService manually to prevent circular componentsToUpgrade (because MessageService use $templateCache that use $http). - data = { - title: 'Error', - message: text, - messageId: messageId, - status: rejection.status, - severity: SEVERITY.ERROR - }; - } else { - // Need to inject the MessageService manually to prevent circular componentsToUpgrade (because MessageService use $templateCache that use $http). - data = { - title: 'Error', - message: rejection.status !== -1 ? rejection.statusText : "Error getting response from server", - messageId: messageId, - status: rejection.status, - severity: SEVERITY.ERROR - }; - } - - let modalsHandler = this.$injector.get('ModalsHandler'); - modalsHandler.openServerMessageModal(data); - - return this.$q.reject(rejection); - } -} diff --git a/catalog-ui/src/app/services/onboarding-service.ts b/catalog-ui/src/app/services/onboarding-service.ts deleted file mode 100644 index 3a6e940c6e..0000000000 --- a/catalog-ui/src/app/services/onboarding-service.ts +++ /dev/null @@ -1,112 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {Component, IComponent} from "../models/components/component"; -import {ICsarComponent} from "../models/csar-component"; -import {IAppConfigurtaion, IApi} from "../models/app-config"; -import {IFileDownload} from "../models/file-download"; -import {Resource} from "../models/components/resource"; -import {ComponentFactory} from "../utils/component-factory"; - -interface IOnboardingService { - getOnboardingComponents():ng.IPromise>; - getComponentFromCsarUuid(csarUuid:string):ng.IPromise; - downloadOnboardingCsar(packageId:string):ng.IPromise; -} - -export class OnboardingService implements IOnboardingService { - - static '$inject' = ['$http', '$q', 'sdcConfig', 'ComponentFactory']; - private api:IApi; - - constructor(private $http:ng.IHttpService, - private $q:ng.IQService, - private sdcConfig:IAppConfigurtaion, - private ComponentFactory:ComponentFactory) { - this.api = sdcConfig.api; - } - - getOnboardingVSPs = ():ng.IPromise> =>{ - let defer = this.$q.defer>(); - this.$http.get(this.api.GET_onboarding) - .then((response:any) => { - defer.resolve(response.data.results); - },(response) => { - defer.reject(response); - }); - - return defer.promise; - }; - - getOnboardingComponents = ():ng.IPromise> => { - let defer = this.$q.defer>(); - this.getOnboardingVSPs().then((onboardingComponents:Array) => { - let componentsList:Array = new Array(); - - onboardingComponents.forEach((obc:ICsarComponent) => { - let component:Component = this.ComponentFactory.createFromCsarComponent(obc); - componentsList.push(component); - }); - - defer.resolve(componentsList); - },(response) => { - defer.reject(response); - }); - - return defer.promise; - }; - - downloadOnboardingCsar = (packageId:string):ng.IPromise => { - let defer = this.$q.defer(); - this.$http({ - url: this.api.GET_onboarding + "/" + packageId, - method: "get", - responseType: "blob" - }) - .then((response:any) => { - defer.resolve(response.data); - }, (err) => { - defer.reject(err); - }); - - return defer.promise; - }; - - getComponentFromCsarUuid = (csarUuid:string):ng.IPromise => { - let defer = this.$q.defer(); - this.$http.get(this.api.root + this.api.GET_component_from_csar_uuid.replace(':csar_uuid', csarUuid)) - .then((response:any) => { - let component:Resource; - // If the status is 400, this means that the component not found. - // I do not want to return error from server, because a popup will appear in client with the error. - // So returning success (200) with status 400. - if (response.data.status !== 400) { - component = new Resource(null, this.$q, response.data); - } - defer.resolve(component); - },(response) => { - defer.reject(response.data); - }); - - return defer.promise; - }; - -} diff --git a/catalog-ui/src/app/services/sharing-service.ts b/catalog-ui/src/app/services/sharing-service.ts deleted file mode 100644 index f4cc2e6d5d..0000000000 --- a/catalog-ui/src/app/services/sharing-service.ts +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {Dictionary} from "app/utils"; - -export class SharingService { - - private uuidMap:Dictionary = new Dictionary(); - - public getUuidValue = (uniqueId:string):string => { - return this.uuidMap.getValue(uniqueId); - }; - - public addUuidValue = (uniqueId:string, uuid:string):void => { - this.uuidMap.setValue(uniqueId, uuid); - }; - - public getUuidMap = ():Dictionary => { - return this.uuidMap; - }; - -} diff --git a/catalog-ui/src/app/utils.ts b/catalog-ui/src/app/utils.ts index 1d2eafb9fb..27c805a762 100644 --- a/catalog-ui/src/app/utils.ts +++ b/catalog-ui/src/app/utils.ts @@ -22,7 +22,6 @@ * Created by ob0695 on 2/23/2017. */ export * from './utils/dictionary/dictionary'; -export * from './utils/artifacts-utils'; export * from'./utils/file-utils' export * from './utils/validation-utils' export * from './utils/component-factory'; diff --git a/catalog-ui/src/app/utils/artifacts-utils.ts b/catalog-ui/src/app/utils/artifacts-utils.ts deleted file mode 100644 index e99b6411c4..0000000000 --- a/catalog-ui/src/app/utils/artifacts-utils.ts +++ /dev/null @@ -1,126 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -import * as _ from "lodash"; -import {ArtifactModel} from "../models/artifacts"; -import {IArtifactResourceFormViewModelScope} from "../view-models/forms/artifact-form/artifact-form-view-model"; -import {Component} from "../models/components/component"; -import {ArtifactGroupType, ArtifactType} from "./constants"; - -export class ArtifactsUtils { - - static '$inject' = [ - '$filter' - ]; - - constructor(private $filter:ng.IFilterService) { - - } - - public getArtifactTypeByState(currentState:string):string { - switch (currentState) { - case "workspace.composition.lifecycle": - return "interface"; - case "workspace.composition.api": - return "api"; - case "workspace.deployment_artifacts": - case "workspace.composition.deployment": - return "deployment"; - case "workspace.composition.artifacts": - return "informational"; - default: - return "informational"; - } - } - - public getTitle(artifactType:string, selectedComponent:Component):string { - switch (artifactType) { - case "interface": - return "Lifecycle Management"; - case "api": - return "API Artifacts"; - case "deployment": - return "Deployment Artifacts"; - case "informational": - return "Informational Artifacts"; - default: - if (!selectedComponent) { - return ""; - } else { - return this.$filter("resourceName")(selectedComponent.name) + ' Artifacts'; - } - } - } - - public setArtifactType = (artifact:ArtifactModel, artifactType:string):void => { - switch (artifactType) { - case "api": - artifact.artifactGroupType = ArtifactGroupType.SERVICE_API; - break; - case "deployment": - artifact.artifactGroupType = ArtifactGroupType.DEPLOYMENT; - break; - default: - artifact.artifactGroupType = ArtifactGroupType.INFORMATION; - break; - } - }; - - public isLicenseType = (artifactType:string):boolean => { - let isLicense:boolean = false; - - if (ArtifactType.VENDOR_LICENSE === artifactType || ArtifactType.VF_LICENSE === artifactType) { - isLicense = true; - } - - return isLicense; - }; - - public removeArtifact = (artifact:ArtifactModel, artifactsArr:Array):void => { - - if (!artifact.mandatory && (ArtifactGroupType.INFORMATION == artifact.artifactGroupType || - ArtifactGroupType.DEPLOYMENT == artifact.artifactGroupType)) { - _.remove(artifactsArr, {uniqueId: artifact.uniqueId}); - } - else { - let artifactToDelete = _.find(artifactsArr, {uniqueId: artifact.uniqueId}); - - delete artifactToDelete.esId; - delete artifactToDelete.description; - delete artifactToDelete.artifactName; - delete artifactToDelete.apiUrl; - } - }; - - public addAnotherAfterSave(scope:IArtifactResourceFormViewModelScope) { - let newArtifact = new ArtifactModel(); - this.setArtifactType(newArtifact, scope.artifactType); - scope.editArtifactResourceModel.artifactResource = newArtifact; - - scope.forms.editForm['description'].$setPristine(); - if (scope.forms.editForm['artifactLabel']) { - scope.forms.editForm['artifactLabel'].$setPristine(); - } - if (scope.forms.editForm['type']) { - scope.forms.editForm['type'].$setPristine(); - } - - } -} diff --git a/catalog-ui/src/app/utils/change-lifecycle-state-handler.ts b/catalog-ui/src/app/utils/change-lifecycle-state-handler.ts index 54497ba187..6a37864fe1 100644 --- a/catalog-ui/src/app/utils/change-lifecycle-state-handler.ts +++ b/catalog-ui/src/app/utils/change-lifecycle-state-handler.ts @@ -17,18 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - -import {ComponentFactory} from "./component-factory"; -import {Component, Service,IAppMenu, IAppConfigurtaion} from "../models"; -import {IEmailModalModel, IEmailModalModel_Email, IEmailModalModel_Data} from "../view-models/modals/email-modal/email-modal-view-model"; -import {AsdcComment} from "../models/comments"; -import {ModalsHandler} from "./modals-handler"; -import {ServiceServiceNg2} from "../ng2/services/component-services/service.service"; -import {EventBusService} from "../ng2/services/event-bus.service"; - -/** - * Created by obarda on 2/11/2016. - */ +import { ServiceServiceNg2 } from 'app/ng2/services/component-services/service.service'; +import { EventBusService } from 'app/ng2/services/event-bus.service'; +import { EVENTS, ValidationUtils } from 'app/utils'; +import { SdcUiCommon, SdcUiComponents, SdcUiServices } from 'onap-ui-angular'; +import { Component, IAppConfigurtaion, IAppMenu, Service } from '../models'; +import { AsdcComment } from '../models/comments'; +import { CommentModalComponent } from '../ng2/components/modals/comment-modal/comment-modal.component'; +import { EventListenerService } from '../services/event-listener-service'; +import { ComponentFactory } from './component-factory'; +import { ModalsHandler } from './modals-handler'; export class ChangeLifecycleStateHandler { @@ -39,167 +37,130 @@ export class ChangeLifecycleStateHandler { '$filter', 'ModalsHandler', 'ServiceServiceNg2', - 'EventBusService' + 'EventBusService', + 'ModalServiceSdcUI', + 'ValidationUtils', + 'EventListenerService' ]; - constructor(private sdcConfig:IAppConfigurtaion, - private sdcMenu:IAppMenu, - private ComponentFactory:ComponentFactory, - private $filter:ng.IFilterService, - private ModalsHandler:ModalsHandler, - private ServiceServiceNg2:ServiceServiceNg2, - private eventBusService:EventBusService) { - + constructor(private sdcConfig: IAppConfigurtaion, + private sdcMenu: IAppMenu, + private componentFactory: ComponentFactory, + private $filter: ng.IFilterService, + private modalsHandler: ModalsHandler, + private serviceServiceNg2: ServiceServiceNg2, + private eventBusService: EventBusService, + private modalService: SdcUiServices.ModalService, + private validationUtils: ValidationUtils, + private eventListenerService: EventListenerService) { } - private actualChangeLifecycleState = (component:Component, data:any, scope:any, onSuccessCallback?:Function, onErrorCallback?:Function):void => { + public changeLifecycleState = (component: Component, data: any, scope: any, onSuccessCallback?: Function, onErrorCallback?: Function) => { + if (data.conformanceLevelModal) { + this.validateConformanceLevel(component, data, scope, onSuccessCallback, onErrorCallback); + } else { + this.actualChangeLifecycleState(component, data, scope, onSuccessCallback, onErrorCallback); + } + } - let self = this; + private actualChangeLifecycleState = (component: Component, data: any, scope: any, onSuccessCallback?: Function, onErrorCallback?: Function) => { + const self = this; - let getContacts = (component:Component):string => { - let testers = this.sdcConfig.testers; - let result:string = testers[component.componentType][component.categories[0].name] ? - testers[component.componentType][component.categories[0].name] : - testers[component.componentType]['default']; - return result; - }; - - let onSuccess = (newComponent:Component):void => { - //scope.isLoading = false; - console.info(component.componentType.toLowerCase + ' change state ', newComponent); + const onSuccess = (newComponent: Component) => { if (onSuccessCallback) { - onSuccessCallback(self.ComponentFactory.createComponent(newComponent), data.url); + onSuccessCallback(self.componentFactory.createComponent(newComponent), data.url); + if (data.url === 'distribution/PROD/activate') { + this.eventListenerService.notifyObservers(EVENTS.ON_DISTRIBUTION_SUCCESS); + } } }; - let onError = (error):void => { + const onError = (error) => { scope.isLoading = false; - console.info('Failed to changeLifecycleState to ', data.url); if (onErrorCallback) { onErrorCallback(error); } }; - let comment:AsdcComment = new AsdcComment(); + const comment: AsdcComment = new AsdcComment(); if (data.alertModal) { // Show alert dialog if defined in menu.json - //------------------------------------------------- - let onOk = (confirmationText):void => { + const onOk: Function = (confirmationText) => { comment.userRemarks = confirmationText; scope.isLoading = true; component.changeLifecycleState(data.url, comment).then(onSuccess, onError); }; - let onCancel = ():void => { - console.info('Cancel pressed'); - scope.isLoading = false; - }; - - let modalTitle = this.sdcMenu.alertMessages[data.alertModal].title; - let modalMessage = this.sdcMenu.alertMessages[data.alertModal].message.format([component.componentType.toLowerCase()]); - this.ModalsHandler.openAlertModal(modalTitle, modalMessage).then(onOk, onCancel); + const modalTitle = this.sdcMenu.alertMessages[data.alertModal].title; + const modalMessage = this.sdcMenu.alertMessages[data.alertModal].message.format([component.componentType.toLowerCase()]); + const modalButton = { + testId: 'OK', + text: this.sdcMenu.alertMessages.okButton, + type: SdcUiCommon.ButtonType.warning, + callback: onOk, + closeModal: true + } as SdcUiComponents.ModalButtonComponent; + this.modalService.openWarningModal(modalTitle, modalMessage, 'alert-modal', [modalButton]); } else if (data.confirmationModal) { // Show confirmation dialog if defined in menu.json - //------------------------------------------------- - let onOk = (confirmationText):void => { - comment.userRemarks = confirmationText; - - if (data.url === "lifecycleState/CHECKIN") { - this.eventBusService.notify("CHECK_IN").subscribe(() => { + let commentModalInstance: SdcUiComponents.ModalComponent; + const onOk = () => { + const confirmationText: string = commentModalInstance.innerModalContent.instance.comment.text; + commentModalInstance.closeModal(); + comment.userRemarks = this.validationUtils.stripAndSanitize(confirmationText); + + if (data.url === 'lifecycleState/CHECKIN') { + this.eventBusService.notify('CHECK_IN').subscribe(() => { scope.isLoading = true; component.changeLifecycleState(data.url, comment).then(onSuccess, onError); }); - } - else { + } else { scope.isLoading = true; component.changeLifecycleState(data.url, comment).then(onSuccess, onError); } }; - let onCancel = ():void => { - console.info('Cancel pressed'); - scope.isLoading = false; - }; - - let modalTitle = this.sdcMenu.confirmationMessages[data.confirmationModal].title; - let modalMessage = this.sdcMenu.confirmationMessages[data.confirmationModal].message.format([component.componentType.toLowerCase()]); - let modalShowComment = this.sdcMenu.confirmationMessages[data.confirmationModal].showComment; - this.ModalsHandler.openConfirmationModal(modalTitle, modalMessage, modalShowComment).then(onOk, onCancel); - - } else if (data.emailModal) { - // Show email dialog if defined in menu.json - //------------------------------------------------- - let onOk = (resource):void => { - if (data.url === "lifecycleState/certificationRequest") { - this.eventBusService.notify("SUBMIT_FOR_TESTING").subscribe(() => { - if (resource) { - onSuccess(resource); - } else { - onError("Error changing life cycle state"); - } - }); - } - else { - if (resource) { - onSuccess(resource); - } else { - onError("Error changing life cycle state"); - } - } - }; - - let onCancel = ():void => { - scope.isLoading = false; - }; - - let emailModel:IEmailModalModel = {}; - emailModel.email = {}; - emailModel.data = {}; - emailModel.title = this.$filter('translate')("EMAIL_MODAL_TITLE"); - emailModel.email.to = getContacts(component); - emailModel.email.subject = this.$filter('translate')("EMAIL_MODAL_SUBJECT", "{'entityName': '" + this.$filter('resourceName')(component.name) + "','entityVersion': '" + component.version + "'}"); - emailModel.email.message = ''; - emailModel.data.component = component; - emailModel.data.stateUrl = data.url; - - this.ModalsHandler.openEmailModal(emailModel).then(onOk, onCancel); - + const modalTitle = this.sdcMenu.confirmationMessages[data.confirmationModal].title; + const modalMessage = this.sdcMenu.confirmationMessages[data.confirmationModal].message.format([component.componentType.toLowerCase()]); + const modalConfig = { + size: 'md', + title: modalTitle, + type: SdcUiCommon.ModalType.custom, + testId: 'confirm-modal', + buttons: [ + { id: 'OK', text: 'OK', callback: onOk, closeModal: false, testId: 'OK' }, + { id: 'cancel', text: 'Cancel', size: 'x-small', type: 'secondary', closeModal: true, testId: 'Cancel' } + ] as SdcUiCommon.IModalButtonComponent[] + } as SdcUiCommon.IModalConfig; + commentModalInstance = this.modalService.openCustomModal(modalConfig, CommentModalComponent, { message: modalMessage }); + commentModalInstance.innerModalContent.instance.onValidationChange.subscribe((isValid) => { + commentModalInstance.getButtonById('OK').disabled = !isValid; + }); } else { // Submit to server only (no modal is shown). scope.isLoading = true; component.changeLifecycleState(data.url, comment).then(onSuccess, onError); } - - } - - public changeLifecycleState = (component:Component, data:any, scope:any, onSuccessCallback?:Function, onErrorCallback?:Function):void => { - - if (data.conformanceLevelModal) { - this.validateConformanceLevel(component, data, scope, onSuccessCallback, onErrorCallback); - } else { - this.actualChangeLifecycleState(component, data, scope, onSuccessCallback, onErrorCallback); - } } - private validateConformanceLevel = (component:Component, data:any, scope:any, onSuccessCallback?:Function, onErrorCallback?:Function):void => { + private validateConformanceLevel = (component: Component, data: any, scope: any, onSuccessCallback?: Function, onErrorCallback?: Function) => { // Validate conformance level if defined in menu.json - //------------------------------------------------- - this.ServiceServiceNg2.validateConformanceLevel(component).subscribe((res:boolean) => { + this.serviceServiceNg2.validateConformanceLevel(component as Service).subscribe((res: boolean) => { if (res === true) { - //conformance level is ok - continue + // Conformance level is ok - continue this.actualChangeLifecycleState(component, data, scope, onSuccessCallback, onErrorCallback); - } else { - //show warning modal - this.ModalsHandler.openConformanceLevelModal() - .then(() => { - //continue distribute - this.actualChangeLifecycleState(component, data, scope, onSuccessCallback, onErrorCallback); - - }).catch(() => { - //reject distribution - this.actualChangeLifecycleState(component, data.conformanceLevelModal, scope, onSuccessCallback, onErrorCallback); - }); + // Show warning modal + const onContinue: Function = () => { + this.actualChangeLifecycleState(component, data, scope, onSuccessCallback, onErrorCallback); + }; + const reject: Function = () => { + this.actualChangeLifecycleState(component, data.conformanceLevelModal, scope, onSuccessCallback, onErrorCallback); + }; + const continueButton = {testId: 'Continue', text: 'Continue', type: SdcUiCommon.ButtonType.primary, callback: onContinue, closeModal: true} as SdcUiComponents.ModalButtonComponent; + const rejectButton = {testId: 'Reject', text: 'Reject', type: SdcUiCommon.ButtonType.secondary, callback: reject, closeModal: true} as SdcUiComponents.ModalButtonComponent; + this.modalService.openInfoModal(this.$filter('translate')('CONFORMANCE_LEVEL_MODAL_TITLE'), + this.$filter('translate')('CONFORMANCE_LEVEL_MODAL_TEXT'), 'conformance-modal', [continueButton, rejectButton]); } }); } diff --git a/catalog-ui/src/app/utils/common-utils.ts b/catalog-ui/src/app/utils/common-utils.ts index 99f7c49a29..eadb92bd4f 100644 --- a/catalog-ui/src/app/utils/common-utils.ts +++ b/catalog-ui/src/app/utils/common-utils.ts @@ -19,11 +19,12 @@ */ import * as _ from "lodash"; -import {Module, AttributeModel, ResourceInstance, PropertyModel, InterfaceModel, OperationModel} from "../models"; +import {Module, AttributeModel, ResourceInstance, PropertyModel, InputFEModel, OperationModel} from "../models"; import {ComponentInstanceFactory} from "./component-instance-factory"; import {InputBEModel, PropertyBEModel, RelationshipModel} from "app/models"; import { PolicyInstance } from "app/models/graph/zones/policy-instance"; import { GroupInstance } from "../models/graph/zones/group-instance"; +import { InterfaceModel } from "../models/operation"; export class CommonUtils { @@ -167,7 +168,7 @@ export class CommonUtils { }); } - + static initInterfaceOperations(interfaces: Array): Array { return _.reduce(interfaces, (acc, interf: InterfaceModel) => { @@ -194,5 +195,6 @@ export class CommonUtils { }, []); } + } diff --git a/catalog-ui/src/app/utils/component-factory.ts b/catalog-ui/src/app/utils/component-factory.ts index 2b134bd2e7..889f6fb43b 100644 --- a/catalog-ui/src/app/utils/component-factory.ts +++ b/catalog-ui/src/app/utils/component-factory.ts @@ -21,7 +21,8 @@ 'use strict'; import * as _ from "lodash"; import {DEFAULT_ICON, ResourceType, ComponentType} from "./constants"; -import {ServiceService, CacheService, ResourceService} from "app/services"; +import {ServiceService, ResourceService} from "app/services"; +import {CacheService} from "app/services-ng2"; import {IMainCategory, ISubCategory, ICsarComponent, Component, Resource, Service} from "app/models"; import {ComponentMetadata} from "../models/component-metadata"; import {ComponentServiceNg2} from "../ng2/services/component-services/component.service"; @@ -71,23 +72,23 @@ export class ComponentFactory { return newResource; }; - public updateComponentFromCsar = (csarComponent:Resource, oldComponent:Resource):Component => { - _.pull(oldComponent.tags, oldComponent.name); - if (!oldComponent.isAlreadyCertified()) { + public updateComponentFromCsar = (csarComponent:Resource, oldComponent: Resource): Component => { + _.pull(oldComponent.tags, oldComponent.name); + if (!oldComponent.isAlreadyCertified()) { oldComponent.name = csarComponent.name; oldComponent.categories = csarComponent.categories; oldComponent.selectedCategory = csarComponent.selectedCategory; } - oldComponent.vendorName = csarComponent.vendorName; - oldComponent.vendorRelease = csarComponent.vendorRelease; - oldComponent.csarUUID = csarComponent.csarUUID; - oldComponent.csarPackageType = csarComponent.csarPackageType; - oldComponent.csarVersion = csarComponent.csarVersion; - oldComponent.packageId = csarComponent.packageId; - oldComponent.description = csarComponent.description; - oldComponent.filterTerm = oldComponent.name + ' ' + oldComponent.description + ' ' + oldComponent.vendorName + ' ' + oldComponent.csarVersion - return oldComponent; - }; + oldComponent.vendorName = csarComponent.vendorName; + oldComponent.vendorRelease = csarComponent.vendorRelease; + oldComponent.csarUUID = csarComponent.csarUUID; + oldComponent.csarPackageType = csarComponent.csarPackageType; + oldComponent.csarVersion = csarComponent.csarVersion; + oldComponent.packageId = csarComponent.packageId; + oldComponent.description = csarComponent.description; + oldComponent.filterTerm = oldComponent.name + ' ' + oldComponent.description + ' ' + oldComponent.vendorName + ' ' + oldComponent.csarVersion; + return oldComponent; + } public createFromCsarComponent = (csar:ICsarComponent):Component => { let newResource:Resource = this.createEmptyComponent(ComponentType.RESOURCE); @@ -126,7 +127,7 @@ export class ComponentFactory { } // Fill the component with details from CSAR - newResource.selectedCategory = selectedCategory && selectedSubCategory ? selectedCategory.name + "_#_" + selectedSubCategory.name : ''; + newResource.categories = categories; newResource.vendorName = csar.vendorName; newResource.vendorRelease = csar.vendorRelease; @@ -136,7 +137,8 @@ export class ComponentFactory { newResource.packageId = csar.packageId; newResource.description = csar.description; newResource.resourceType = csar.resourceType; - newResource.filterTerm = newResource.name + ' ' + newResource.description + ' ' + newResource.vendorName + ' ' + newResource.csarVersion + newResource.selectedCategory = selectedCategory && selectedSubCategory ? selectedCategory.name + "_#_" + selectedSubCategory.name : ''; + newResource.filterTerm = newResource.name + ' ' + newResource.description + ' ' + newResource.vendorName + ' ' + newResource.csarVersion; return newResource; }; @@ -183,7 +185,7 @@ export class ComponentFactory { let deferred = this.$q.defer(); let component = this.createEmptyComponent(componentType); component.setUniqueId(componentId); - this.ComponentServiceNg2.getComponentMetadata(component).subscribe((response:ComponentGenericResponse) => { + this.ComponentServiceNg2.getComponentMetadata(component.uniqueId, component.componentType).subscribe((response:ComponentGenericResponse) => { component.setComponentMetadata(response.metadata); deferred.resolve(component); }); diff --git a/catalog-ui/src/app/utils/component-instance-factory.ts b/catalog-ui/src/app/utils/component-instance-factory.ts index 25916cc055..03abd96a77 100644 --- a/catalog-ui/src/app/utils/component-instance-factory.ts +++ b/catalog-ui/src/app/utils/component-instance-factory.ts @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,14 +21,14 @@ * Created by obarda on 3/7/2016. */ 'use strict'; -import {ComponentInstance, ServiceInstance, ResourceInstance, Component, ServiceProxyInstance} from "../models"; -import {ComponentType} from "app/utils"; -import {LeftPaletteComponent} from "../models/components/displayComponent"; +import { ComponentType } from 'app/utils'; +import { Component, ComponentInstance, ResourceInstance, ServiceInstance, ServiceProxyInstance } from '../models'; +import { LeftPaletteComponent } from '../models/components/displayComponent'; export class ComponentInstanceFactory { - static createComponentInstance(componentInstance:ComponentInstance):ComponentInstance { - let newComponentInstance:ComponentInstance; + static createComponentInstance(componentInstance: ComponentInstance): ComponentInstance { + let newComponentInstance: ComponentInstance; switch (componentInstance.originType) { case ComponentType.SERVICE: newComponentInstance = new ServiceInstance(componentInstance); @@ -41,10 +41,10 @@ export class ComponentInstanceFactory { break; } return newComponentInstance; - }; + } - public createEmptyComponentInstance = (componentInstanceType?:string):ComponentInstance => { - let newComponentInstance:ComponentInstance; + static createEmptyComponentInstance = (componentInstanceType?: string): ComponentInstance => { + let newComponentInstance: ComponentInstance; switch (componentInstanceType) { case ComponentType.SERVICE: newComponentInstance = new ServiceInstance(); @@ -57,25 +57,32 @@ export class ComponentInstanceFactory { break; } return newComponentInstance; - }; + } - public createComponentInstanceFromComponent = (component:LeftPaletteComponent):ComponentInstance => { - let newComponentInstance:ComponentInstance = this.createEmptyComponentInstance(component.componentType); + static createComponentInstanceFromComponent = (component: LeftPaletteComponent): ComponentInstance => { + const newComponentInstance: ComponentInstance = ComponentInstanceFactory.createEmptyComponentInstance(component.componentType); newComponentInstance.uniqueId = component.uniqueId + (new Date()).getTime(); newComponentInstance.posX = 0; newComponentInstance.posY = 0; newComponentInstance.name = component.name; newComponentInstance.componentVersion = component.version; - newComponentInstance.originType = component.getComponentSubType(); - if(component.getComponentSubType() === ComponentType.SERVICE){ - newComponentInstance.originType = ComponentType.SERVICE_PROXY - } - //new component instance -> req. & cap. are added on successful instance creation + newComponentInstance.originType = getOriginType(component); newComponentInstance.requirements = component.requirements; newComponentInstance.capabilities = component.capabilities; newComponentInstance.icon = component.icon; newComponentInstance.componentUid = component.uniqueId; return newComponentInstance; - }; + function getOriginType(component: LeftPaletteComponent): string { + if (component.componentSubType) { + return component.componentSubType; + } else { + if (component.componentType === ComponentType.SERVICE) { + return ComponentType.SERVICE_PROXY; + } else { + return component.resourceType; + } + } + } + } } diff --git a/catalog-ui/src/app/utils/constants.ts b/catalog-ui/src/app/utils/constants.ts index 9d3bf104ee..e82322e0de 100644 --- a/catalog-ui/src/app/utils/constants.ts +++ b/catalog-ui/src/app/utils/constants.ts @@ -43,8 +43,20 @@ export class ComponentType { export class ServerTypeUrl { static RESOURCES = 'resources/'; static SERVICES = 'services/'; + + public static toServerTypeUrl(componentType: ComponentType) : string { + if (componentType == ComponentType.SERVICE) { + return ServerTypeUrl.SERVICES.slice(0,-1); + } else if (componentType == ComponentType.RESOURCE) { + return ServerTypeUrl.RESOURCES.slice(0,-1); + } else { + return undefined; + } + } } + + export class ResourceType { static VF = 'VF'; static VL = 'VL'; @@ -57,6 +69,11 @@ export class ResourceType { static CR = 'CR'; } +export class SdcElementType { + static GROUP = 'GROUP'; + static POLICY = 'POLICY'; + static SERVICE_PROXY = 'ServiceProxy' +} export class ComponentState { static CERTIFICATION_IN_PROGRESS = 'CERTIFICATION_IN_PROGRESS'; static CERTIFIED = 'CERTIFIED'; @@ -76,9 +93,15 @@ export class ArtifactGroupType { static DEPLOYMENT = "DEPLOYMENT"; static INFORMATION = "INFORMATIONAL"; static SERVICE_API = "SERVICE_API"; + static TOSCA = "TOSCA"; } export class ArtifactType { + + static DEPLOYMENT = "DEPLOYMENT"; + static INFORMATION = "INFORMATIONAL"; + static SERVICE_API = "SERVICE_API"; + static HEAT_ENV = "HEAT_ENV"; static HEAT = "HEAT"; static HEAT_VOL = "HEAT_VOL"; static HEAT_NET = "HEAT_NET"; @@ -202,6 +225,7 @@ export class ServerErrors { static ERROR_TITLE = 'Error'; static DEFAULT_ERROR = 'Error getting response from server'; static MESSAGE_ERROR = 'Wrong error format from server'; + static DOWNLOAD_ERROR = 'Download error'; } export class GraphColors { @@ -255,6 +279,8 @@ export class States { public static WORKSPACE_ACTIVITY_LOG = 'workspace.activity_log'; public static WORKSPACE_DEPLOYMENT_ARTIFACTS = 'workspace.deployment_artifacts'; public static WORKSPACE_PROPERTIES = 'workspace.properties'; + public static WORKSPACE_SERVICE_INPUTS = 'workspace.service_inputs'; + public static WORKSPACE_RESOURCE_INPUTS = 'workspace.resource_inputs'; public static WORKSPACE_ATTRIBUTES = 'workspace.attributes'; public static WORKSPACE_INFORMATION_ARTIFACTS = 'workspace.information_artifacts'; public static WORKSPACE_TOSCA_ARTIFACTS = 'workspace.tosca_artifacts'; @@ -287,6 +313,7 @@ export class EVENTS { static SHOW_LOADER_EVENT = "showLoaderEvent"; static HIDE_LOADER_EVENT = "hideLoaderEvent"; static UPDATE_PANEL = 'updatePanel'; + static ON_DISTRIBUTION_SUCCESS = 'onDistributionSuccess'; } @@ -312,6 +339,7 @@ export class GRAPH_EVENTS { static ON_PALETTE_COMPONENT_HOVER_OUT = 'onPaletteComponentHoverOut'; static ON_PALETTE_COMPONENT_DRAG_START = 'onPaletteComponentDragStart'; static ON_PALETTE_COMPONENT_DRAG_ACTION = 'onPaletteComponentDragAction'; + static ON_PALETTE_COMPONENT_DROP = 'onPaletteComponentDrop'; static ON_PALETTE_COMPONENT_SHOW_POPUP_PANEL = 'onPaletteComponentShowPopupPanel'; static ON_PALETTE_COMPONENT_HIDE_POPUP_PANEL = 'onPaletteComponentHidePopupPanel'; static ON_COMPONENT_INSTANCE_NAME_CHANGED = 'onComponentInstanceNameChanged'; @@ -329,6 +357,7 @@ export class GRAPH_EVENTS { static ON_CANVAS_TAG_END = 'onCanvasTagEnd'; static ON_POLICY_INSTANCE_UPDATE = 'onPolicyInstanceUpdate'; static ON_GROUP_INSTANCE_UPDATE = 'onGroupInstanceUpdate'; + static ON_SERVICE_PATH_CREATED = 'onServicePathCreated'; } export class DEPENDENCY_EVENTS { @@ -349,6 +378,7 @@ export class COMPONENT_FIELDS { static COMPONENT_INFORMATIONAL_ARTIFACTS = "artifacts"; static COMPONENT_PROPERTIES = "properties"; static COMPONENT_CAPABILITIES = "capabilities"; + static COMPONENT_CAPABILITIES_PROPERTIES = "instanceCapabiltyProperties"; static COMPONENT_REQUIREMENTS = "requirements"; static COMPONENT_TOSCA_ARTIFACTS = "toscaArtifacts"; static COMPONENT_POLICIES = "policies"; @@ -357,6 +387,8 @@ export class COMPONENT_FIELDS { static COMPONENT_INSTANCES_INTERFACES = "componentInstancesInterfaces"; static COMPONENT_NON_EXCLUDED_GROUPS = "nonExcludedGroups"; static COMPONENT_NON_EXCLUDED_POLICIES = "nonExcludedPolicies"; + static FORWARDING_PATHS = "forwardingPaths"; + static SERVICE_API_ARTIFACT = "serviceApiArtifacts"; } export class SERVICE_FIELDS { diff --git a/catalog-ui/src/app/utils/menu-handler.ts b/catalog-ui/src/app/utils/menu-handler.ts index eaef63fcc7..e17012a45e 100644 --- a/catalog-ui/src/app/utils/menu-handler.ts +++ b/catalog-ui/src/app/utils/menu-handler.ts @@ -40,7 +40,6 @@ export class MenuItem { alertModal:string; conformanceLevelModal: boolean; // Call validateConformanceLevel API and shows conformanceLevelModal if necessary, then continue with action or invokes another action confirmationModal:string; // Open confirmation modal (user should select "OK" or "Cancel"), and continue with the action. - emailModal:string; // Open email modal (user should fill email details), and continue with the action. url:string; // Data added to menu item, in case the function need to use it, example: for function "changeLifecycleState", I need to pass also the state "CHECKOUT" that I want the state to change to. diff --git a/catalog-ui/src/app/utils/modals-handler.ts b/catalog-ui/src/app/utils/modals-handler.ts index 903175f199..342f03f290 100644 --- a/catalog-ui/src/app/utils/modals-handler.ts +++ b/catalog-ui/src/app/utils/modals-handler.ts @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,25 +18,13 @@ * ============LICENSE_END========================================================= */ -import {PropertyModel, Component, ArtifactModel, Distribution, InputModel, DisplayModule, InputPropertyBase} from "../models"; -import {IEmailModalModel} from "../view-models/modals/email-modal/email-modal-view-model"; -import {IClientMessageModalModel} from "../view-models/modals/message-modal/message-client-modal/client-message-modal-view-model"; -import {IServerMessageModalModel} from "../view-models/modals/message-modal/message-server-modal/server-message-modal-view-model"; -import {IConfirmationModalModel} from "../view-models/modals/confirmation-modal/confirmation-modal-view-model"; -import {ModalType} from "./constants"; -import {AttributeModel} from "../models/attributes"; +import { Component, DisplayModule , PropertyModel } from '../models'; +import { ComponentMetadata } from '../models/component-metadata'; export interface IModalsHandler { - - openDistributionStatusModal (distribution:Distribution, status:string, component:Component):ng.IPromise; - openConfirmationModal (title:string, message:string, showComment:boolean, size?:string):ng.IPromise; - openAlertModal (title:string, message:string, size?:string):ng.IPromise; - openEmailModal(emailModel:IEmailModalModel):ng.IPromise; - openServerMessageModal(data:IServerMessageModalModel):ng.IPromise; - openClientMessageModal(data:IClientMessageModalModel):ng.IPromise; - openArtifactModal(artifact:ArtifactModel, component:Component):ng.IPromise; - openEditPropertyModal(property:PropertyModel, component:Component, filteredProperties:Array, isPropertyOwnValue:boolean, propertyOwnerType:string, propertyOwnerId:string):ng.IPromise; + openEditPropertyModal(property: PropertyModel, component: Component, filteredProperties: PropertyModel[], isPropertyOwnValue: boolean, + propertyOwnerType: string, propertyOwnerId: string): ng.IPromise; } export class ModalsHandler implements IModalsHandler { @@ -46,230 +34,27 @@ export class ModalsHandler implements IModalsHandler { '$q' ]; - constructor(private $uibModal:ng.ui.bootstrap.IModalService, - private $q:ng.IQService) { + constructor(private $uibModal: ng.ui.bootstrap.IModalService, + private $q: ng.IQService) { } - - - - openDistributionStatusModal = (distribution:Distribution, status:string, component:Component):ng.IPromise => { - let deferred = this.$q.defer(); - let modalOptions:ng.ui.bootstrap.IModalSettings = { - templateUrl: '../view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view.html', - controller: 'Sdc.ViewModels.DistributionStatusModalViewModel', - size: 'sdc-xl', - backdrop: 'static', - resolve: { - data: ():any => { - return { - 'distribution': distribution, - 'status': status, - 'component': component - }; - } - } - }; - let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); - deferred.resolve(modalInstance.result); - return deferred.promise; - }; - - - openAlertModal = (title:string, message:string, size?:string):ng.IPromise => { - return this.openConfirmationModalBase(title, message, false, ModalType.ALERT, size); - }; - - openConfirmationModal = (title:string, message:string, showComment:boolean, size?:string):ng.IPromise => { - return this.openConfirmationModalBase(title, message, showComment, ModalType.STANDARD, size); - }; - - private openConfirmationModalBase = (title:string, message:string, showComment:boolean, type:ModalType, size?:string):ng.IPromise => { - let deferred = this.$q.defer(); - let modalOptions:ng.ui.bootstrap.IModalSettings = { - templateUrl: '../view-models/modals/confirmation-modal/confirmation-modal-view.html', - controller: 'Sdc.ViewModels.ConfirmationModalViewModel', - size: size ? size : 'sdc-sm', - backdrop: 'static', - resolve: { - confirmationModalModel: ():IConfirmationModalModel => { - let model:IConfirmationModalModel = { - title: title, - message: message, - showComment: showComment, - type: type - }; - return model; - } - } - }; - - let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); - deferred.resolve(modalInstance.result); - return deferred.promise; - }; - - openEmailModal = (emailModel:IEmailModalModel):ng.IPromise => { - - let deferred = this.$q.defer(); - let modalOptions:ng.ui.bootstrap.IModalSettings = { - templateUrl: '../view-models/modals/email-modal/email-modal-view.html', - controller: 'Sdc.ViewModels.EmailModalViewModel', - size: 'sdc-sm', - backdrop: 'static', - resolve: { - emailModalModel: ():IEmailModalModel => { - return emailModel; - } - } - }; - let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); - deferred.resolve(modalInstance.result); - return deferred.promise; - - }; - - openServerMessageModal = (data:IServerMessageModalModel):ng.IPromise => { - let deferred = this.$q.defer(); - let modalOptions:ng.ui.bootstrap.IModalSettings = { - templateUrl: '../view-models/modals/message-modal/message-server-modal/server-message-modal-view.html', - controller: 'Sdc.ViewModels.ServerMessageModalViewModel', - size: 'sdc-sm', - backdrop: 'static', - resolve: { - serverMessageModalModel: ():IServerMessageModalModel => { - return data; - } - } - }; - - let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); - deferred.resolve(modalInstance.result); - return deferred.promise; - }; - - openClientMessageModal = (data:IClientMessageModalModel):ng.IPromise => { - let deferred = this.$q.defer(); - let modalOptions:ng.ui.bootstrap.IModalSettings = { - templateUrl: '../view-models/modals/message-modal/message-client-modal/client-message-modal-view.html', - controller: 'Sdc.ViewModels.ClientMessageModalViewModel', - size: 'sdc-sm', - backdrop: 'static', - resolve: { - clientMessageModalModel: ():IClientMessageModalModel => { - return data; - } - } - }; - let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); - deferred.resolve(modalInstance); - return deferred.promise; - }; - - openOnboadrdingModal = (okButtonText:string, currentCsarUUID?:string, currentCsarVersion?:string):ng.IPromise => { - let deferred = this.$q.defer(); - let modalOptions:ng.ui.bootstrap.IModalSettings = { - templateUrl: '../view-models/modals/onboarding-modal/onboarding-modal-view.html', - controller: 'Sdc.ViewModels.OnboardingModalViewModel', - size: 'sdc-xl', - backdrop: 'static', - resolve: { - okButtonText: ():string=> { - return okButtonText; - }, - currentCsarUUID: ():string=> { - return currentCsarUUID || null; - }, - currentCsarVersion: ():string=> { - return currentCsarVersion || null; - } - } - }; - let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); - deferred.resolve(modalInstance.result); - return deferred.promise; - }; - - openUpdateIconModal = (component: Component):ng.IPromise => { - let deferred = this.$q.defer(); - let modalOptions:ng.ui.bootstrap.IModalSettings = { + openUpdateIconModal = (component: Component): ng.IPromise => { + const deferred = this.$q.defer(); + const modalOptions: ng.ui.bootstrap.IModalSettings = { templateUrl: '../view-models/modals/icons-modal/icons-modal-view.html', controller: 'Sdc.ViewModels.IconsModalViewModel', size: 'sdc-auto', backdrop: 'static', resolve: { - component: ():Component => { - return component; - } - } - }; - let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); - deferred.resolve(modalInstance.result); - return deferred.promise; - }; - - openEditEnvParametersModal = (artifactResource:ArtifactModel, component?:Component):ng.IPromise => { - let deferred = this.$q.defer(); - let modalOptions:ng.ui.bootstrap.IModalSettings = { - templateUrl: '../view-models/forms/env-parameters-form/env-parameters-form.html', - controller: 'Sdc.ViewModels.EnvParametersFormViewModel', - size: 'sdc-xl', - backdrop: 'static', - resolve: { - artifact: ():ArtifactModel => { - return artifactResource; - }, - component: ():Component => { + component: (): Component => { return component; } } }; - let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); + const modalInstance: ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); deferred.resolve(modalInstance.result); return deferred.promise; - }; - - openEditInputValueModal = (input:InputModel):ng.IPromise => { - let deferred = this.$q.defer(); - let modalOptions:ng.ui.bootstrap.IModalSettings = { - templateUrl: '../view-models/forms/input-form/input-form-view.html', - controller: 'Sdc.ViewModels.InputFormViewModel', - size: 'sdc-md', - backdrop: 'static', - resolve: { - input: ():InputModel => { - return input; - } - } - }; - let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); - deferred.resolve(modalInstance.result); - return deferred.promise; - }; - - openArtifactModal = (artifact:ArtifactModel, component:Component):ng.IPromise => { - let deferred = this.$q.defer(); - let modalOptions:ng.ui.bootstrap.IModalSettings = { - templateUrl: '../view-models/forms/artifact-form/artifact-form-view.html', - controller: 'Sdc.ViewModels.ArtifactResourceFormViewModel', - size: 'sdc-md', - backdrop: 'static', - keyboard: false, - resolve: { - artifact: ():ArtifactModel => { - return artifact; - }, - component: ():Component => { - return component; - } - } - }; - - let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); - deferred.resolve(modalInstance.result); - return deferred.promise; - }; - + } /** * @@ -281,158 +66,113 @@ export class ModalsHandler implements IModalsHandler { * @param isPropertyValueOwner - boolean telling if the component is eligible of editing the property * @returns {IPromise} - Promise telling if the modal has opened or not */ - openEditPropertyModal = (property:PropertyModel, component:Component, filteredProperties:Array, isPropertyValueOwner:boolean, propertyOwnerType:string, propertyOwnerId:string):ng.IPromise => { - let deferred = this.$q.defer(); + openEditPropertyModal = (property: PropertyModel, component: Component | ComponentMetadata, filteredProperties: PropertyModel[], + isPropertyValueOwner: boolean, propertyOwnerType: string, propertyOwnerId: string): ng.IPromise => { + const deferred = this.$q.defer(); - let modalOptions:ng.ui.bootstrap.IModalSettings = { + const modalOptions: ng.ui.bootstrap.IModalSettings = { templateUrl: '../view-models/forms/property-forms/component-property-form/property-form-view.html', controller: 'Sdc.ViewModels.PropertyFormViewModel', size: 'sdc-l', backdrop: 'static', keyboard: false, resolve: { - property: ():PropertyModel => { + property: (): PropertyModel => { return property; }, - component: ():Component => { - return component; + component: (): Component => { + return component as Component; }, - filteredProperties: ():Array => { + filteredProperties: (): PropertyModel[] => { return filteredProperties; }, - isPropertyValueOwner: ():boolean => { + isPropertyValueOwner: (): boolean => { return isPropertyValueOwner; }, - propertyOwnerType: ():string => { + propertyOwnerType: (): string => { return propertyOwnerType; }, - propertyOwnerId: ():string => { + propertyOwnerId: (): string => { return propertyOwnerId; } } }; - let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); + const modalInstance: ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); deferred.resolve(modalInstance.result); return deferred.promise; - }; - + } - openEditModulePropertyModal = (property:PropertyModel, component:Component, selectedModule:DisplayModule, filteredProperties:Array):ng.IPromise => { - let deferred = this.$q.defer(); + /** + * + * This function openes up the edit property modal + * + * @param property - the property to edit + * @param filteredProperties - the filtered properties list to scroll between in the edit modal + * @param isPropertyValueOwner - boolean telling if the component is eligible of editing the property + * @returns {IPromise} - Promise telling if the modal has opened or not + */ + newOpenEditPropertyModal = (property: PropertyModel, filteredProperties: PropertyModel[], isPropertyValueOwner: boolean, propertyOwnerType: string, propertyOwnerId: string): ng.IPromise => { + const deferred = this.$q.defer(); - let modalOptions:ng.ui.bootstrap.IModalSettings = { - templateUrl: '../view-models/forms/property-forms/base-property-form/property-form-base-view.html', - controller: 'Sdc.ViewModels.ModulePropertyView', + const modalOptions: ng.ui.bootstrap.IModalSettings = { + templateUrl: '../view-models/forms/property-forms/component-property-form/property-form-view.html', + controller: 'Sdc.ViewModels.PropertyFormViewModel', size: 'sdc-l', backdrop: 'static', keyboard: false, resolve: { - originalProperty: ():PropertyModel => { + property: (): PropertyModel => { return property; }, - component: ():Component => { - return component; + filteredProperties: (): PropertyModel[] => { + return filteredProperties; }, - selectedModule: ():DisplayModule => { - return selectedModule; + isPropertyValueOwner: (): boolean => { + return isPropertyValueOwner; }, - filteredProperties: ():Array => { - return filteredProperties; + propertyOwnerType: (): string => { + return propertyOwnerType; + }, + propertyOwnerId: (): string => { + return propertyOwnerId; } } }; - let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); + const modalInstance: ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); deferred.resolve(modalInstance.result); return deferred.promise; - }; + } - openSelectDataTypeModal = (property:PropertyModel, component:Component, filteredProperties:Array, propertiesMap:Array):ng.IPromise => { - let deferred = this.$q.defer(); + openEditModulePropertyModal = (property: PropertyModel, component: Component, selectedModule: DisplayModule, filteredProperties: PropertyModel[]): ng.IPromise => { + const deferred = this.$q.defer(); - let modalOptions:ng.ui.bootstrap.IModalSettings = { + const modalOptions: ng.ui.bootstrap.IModalSettings = { templateUrl: '../view-models/forms/property-forms/base-property-form/property-form-base-view.html', - controller: 'Sdc.ViewModels.SelectDataTypeViewModel', + controller: 'Sdc.ViewModels.ModulePropertyView', size: 'sdc-l', backdrop: 'static', keyboard: false, resolve: { - originalProperty: ():PropertyModel => { + originalProperty: (): PropertyModel => { return property; }, - component: ():Component => { - return component; - }, - filteredProperties: ():Array => { - return filteredProperties; + component: (): Component => { + return component as Component; }, - propertiesMap: ():Array=> { - return propertiesMap; - } - } - }; - - let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); - deferred.resolve(modalInstance.result); - return deferred.promise; - }; - - public openEditAttributeModal = (attribute:AttributeModel, component: Component):void => { - - let modalOptions:ng.ui.bootstrap.IModalSettings = { - templateUrl: '../view-models/forms/attribute-form/attribute-form-view.html', - controller: 'Sdc.ViewModels.AttributeFormViewModel', - size: 'sdc-md', - backdrop: 'static', - keyboard: false, - resolve: { - attribute: ():AttributeModel => { - return attribute; + selectedModule: (): DisplayModule => { + return selectedModule; }, - component: ():Component => { - return component; - } - } - }; - this.$uibModal.open(modalOptions); - }; - - public openUpdateComponentInstanceNameModal = (currentComponent: Component):ng.IPromise => { - let deferred = this.$q.defer(); - - let modalOptions:ng.ui.bootstrap.IModalSettings = { - templateUrl: '../view-models/forms/resource-instance-name-form/resource-instance-name-view.html', - controller: 'Sdc.ViewModels.ResourceInstanceNameViewModel', - size: 'sdc-sm', - backdrop: 'static', - resolve: { - component: ():Component => { - return currentComponent; + filteredProperties: (): PropertyModel[] => { + return filteredProperties; } } }; - let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); - deferred.resolve(modalInstance.result); - return deferred.promise; - }; - - public openConformanceLevelModal = ():ng.IPromise => { - let deferred = this.$q.defer(); - let modalOptions:ng.ui.bootstrap.IModalSettings = { - templateUrl: '../view-models/modals/conformance-level-modal/conformance-level-modal-view.html', - controller: 'Sdc.ViewModels.ConformanceLevelModalViewModel', - size: 'sdc-sm', - backdrop: 'static', - resolve: { - - } - }; - - let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); + const modalInstance: ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); deferred.resolve(modalInstance.result); return deferred.promise; - }; + } } diff --git a/catalog-ui/src/app/utils/validation-utils.ts b/catalog-ui/src/app/utils/validation-utils.ts index cd90ba7752..b7e43f79ba 100644 --- a/catalog-ui/src/app/utils/validation-utils.ts +++ b/catalog-ui/src/app/utils/validation-utils.ts @@ -97,25 +97,25 @@ export class ValidationUtils { } }; - public getPropertyListPatterns():IMapRegex { + public static getPropertyListPatterns():IMapRegex { return { - integer: /^(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+)(,?(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+))*$/, - string: /^"[\u0000-\u0021\u0023-\u00BF]+"(\s*,?\s*"[\u0000-\u0021\u0023-\u00BF]+")*$/, - boolean: /^([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee])(,?([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee]))*$/, - float: /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?(,?[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?f?)*$/ + integer: /^$|^(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+)(,?(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+))*$/, + string: /^$|^"[\u0000-\u0021\u0023-\u00BF]+"(\s*,?\s*"[\u0000-\u0021\u0023-\u00BF]+")*$/, + boolean: /^$|^([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee])(,?([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee]))*$/, + float: /^$|^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?(,?[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?f?)*$/ }; } - public getPropertyMapPatterns():IMapRegex { + public static getPropertyMapPatterns():IMapRegex { return { - integer: /^"\w+"\s*:\s?(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+)+(\s*,?\s*"\w+"\s?:\s?(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+)+)*$/, - string: /^"\w+"\s?:\s?"[\u0000-\u0021\u0023-\u00BF]*"(\s*,?\s*"\w+"\s?:\s?"[\u0000-\u0021\u0023-\u00BF]*")*$/, - boolean: /^"\w+"\s?:\s?([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee])(\s*,?\s*"\w+"\s?:\s?([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee]))*$/, - float: /^"\w+"\s?:\s?[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?f?(\s*,?\s*"\w+"\s?:\s?[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?f?)*$/ + integer: /^$|^"\w+"\s*:\s?(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+)+(\s*,?\s*"\w+"\s?:\s?(0|[-+]?[1-9][0-9]*|[-+]?0x[0-9a-fA-F]+|[-+]?0o[0-7]+)+)*$/, + string: /^$|^"\w+"\s?:\s?"[\u0000-\u0021\u0023-\u00BF]*"(\s*,?\s*"\w+"\s?:\s?"[\u0000-\u0021\u0023-\u00BF]*")*$/, + boolean: /^$|^"\w+"\s?:\s?([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee])(\s*,?\s*"\w+"\s?:\s?([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee]))*$/, + float: /^$|^"\w+"\s?:\s?[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?f?(\s*,?\s*"\w+"\s?:\s?[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?f?)*$/ }; } - public validateUniqueKeys(viewValue:string):boolean { + public static validateUniqueKeys(viewValue: string): boolean { if (!viewValue) { return true; //allow empty value } diff --git a/catalog-ui/src/app/view-models/admin-dashboard/admin-dashboard-view-model.ts b/catalog-ui/src/app/view-models/admin-dashboard/admin-dashboard-view-model.ts index c9ffe470f0..40a9e8fde1 100644 --- a/catalog-ui/src/app/view-models/admin-dashboard/admin-dashboard-view-model.ts +++ b/catalog-ui/src/app/view-models/admin-dashboard/admin-dashboard-view-model.ts @@ -19,7 +19,7 @@ */ 'use strict'; -import {CacheService} from "app/services"; +import {CacheService} from "app/services-ng2"; import {IAppConfigurtaion} from "app/models"; interface IAdminDashboardViewModelScope extends ng.IScope { diff --git a/catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management-view-model.ts b/catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management-view-model.ts index c99f9e874d..bb4c44d8da 100644 --- a/catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management-view-model.ts +++ b/catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management-view-model.ts @@ -20,7 +20,8 @@ 'use strict'; import {ModalsHandler, ValidationUtils} from "app/utils"; -import {CacheService, ICategoryResource} from "app/services"; +import {ICategoryResource} from "app/services"; +import {CacheService} from "app/services-ng2"; import {IAppConfigurtaion} from "app/models"; import {ComponentType} from "../../../utils/constants"; @@ -138,58 +139,6 @@ export class CategoryManagementViewModel { }; - scope.deleteCategory = (category:ICategoryResource, subCategory:ICategoryResource):void => { - - let onOk = ():void => { - - scope.isLoading = true; - let type:string = scope.type; - - let onError = (response):void => { - scope.isLoading = false; - console.info('onFaild', response); - }; - - let onSuccess = (response:any):void => { - let arr:Array; - - if (!subCategory) { - arr = this.$scope[type + 'Categories']; - arr.splice(arr.indexOf(category), 1); - if (category === scope.selectedCategory) { - scope.selectedCategory = null; - scope.selectedSubCategory = null; - } - } else { - arr = category.subcategories; - arr.splice(arr.indexOf(subCategory), 1); - } - - scope.isLoading = false; - }; - - if (!subCategory) { - category.$delete({ - types: type + "s", - categoryId: category.uniqueId - } - , onSuccess, onError); - } else { - category.$deleteSubCategory({ - types: type + "s", - categoryId: category.uniqueId, - subCategoryId: subCategory.uniqueId, - } - , onSuccess, onError); - } - }; - let modelType:string = subCategory ? 'sub category' : 'category'; - let title:string = this.$filter('translate')("DELETE_CATEGORY_MODAL_HEADER", "{'modelType': '" + modelType + "' }"); - let message:string = this.$filter('translate')("DELETE_CATEGORY_MODAL_CATEGORY_NAME", "{'modelType': '" + modelType + "' }"); - - this.ModalsHandler.openConfirmationModal(title, message, false, 'sdc-xsm').then(onOk); - }; - this.$scope.serviceCategories = this.cacheService.get('serviceCategories'); this.$scope.resourceCategories = this.cacheService.get('resourceCategories'); } diff --git a/catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management-view.html b/catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management-view.html index d7ee87e2e7..30b71f28e2 100644 --- a/catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management-view.html +++ b/catalog-ui/src/app/view-models/admin-dashboard/category-management/category-management-view.html @@ -36,9 +36,6 @@ data-ng-click="selectCategory(category)" data-tests-id="{{ type === SERVICE ? 'servicecategory' : 'resourcecategory' }}"> {{category.name}} - - -
    @@ -56,9 +53,6 @@ data-ng-click="selectSubCategory(subcategory)" data-tests-id="subcategory"> {{subcategory.name}} - - - diff --git a/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view-model.ts b/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view-model.ts index 45232b7a61..43ae75e048 100644 --- a/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view-model.ts +++ b/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view-model.ts @@ -20,55 +20,40 @@ 'use strict'; import * as _ from "lodash"; -import {ModalsHandler} from "app/utils"; -import {User, IUserProperties, IUser, IAppConfigurtaion} from "app/models"; -import {UserService} from "../../../ng2/services/user.service"; +import { User, IUserProperties, IUser, IAppConfigurtaion } from "app/models"; +import { UserService } from "../../../ng2/services/user.service"; +import { SdcUiCommon, SdcUiServices, SdcUiComponents } from "onap-ui-angular"; +import { AuthenticationService } from "app/ng2/services/authentication.service"; interface IUserManagementViewModelScope extends ng.IScope { - sdcConfig:IAppConfigurtaion; usersList:Array; isLoading:boolean; - isNewUser:boolean; sortBy:string; reverse:boolean; tableHeadersList:any; - roles:Array; - newUser:IUser; - currentUser:IUserProperties; - userIdValidationPattern:RegExp; - editForm:ng.IFormController; getAllUsers():void; - editUserRole(user:IUserProperties); sort(sortBy:string):void; - createUser():void; - deleteUser(userId:string):void; - onEditUserPressed(user:IUserProperties):void; - saveUserChanges(user:IUserProperties):void; getTitle(role:string):string; - clearForm():void; - } export class UserManagementViewModel { static '$inject' = [ '$scope', - 'sdcConfig', 'UserServiceNg2', - 'UserIdValidationPattern', + 'AuthenticationServiceNg2', '$filter', - 'ModalsHandler' + 'ModalServiceSdcUI' ]; constructor(private $scope:IUserManagementViewModelScope, - private sdcConfig:IAppConfigurtaion, private userService:UserService, - private UserIdValidationPattern:RegExp, + private authService:AuthenticationService, private $filter:ng.IFilterService, - private ModalsHandler:ModalsHandler) { + private modalService:SdcUiServices.ModalService) { - this.initScope(); + setTimeout(this.initScope, 1000); } @@ -89,13 +74,8 @@ export class UserManagementViewModel { this.userService.getAllUsers().subscribe(onSuccess, onError); }; - private updateUserFilterTerm = (user:IUserProperties):void => { - user.filterTerm = user.firstName + ' ' + user.lastName + ' ' + user.userId + ' ' + user.email + ' ' + user.role + ' ' + this.$filter('date')(user.lastLoginTime, "MM/dd/yyyy"); - }; - private initScope = ():void => { let self = this; - this.$scope.tableHeadersList = [{title: "First Name", property: 'firstName'}, { title: "Last Name", property: 'lastName' @@ -107,116 +87,18 @@ export class UserManagementViewModel { title: "Last Active", property: 'lastLoginTime' }]; - this.$scope.userIdValidationPattern = this.UserIdValidationPattern; this.$scope.sortBy = 'lastLoginTime'; this.$scope.reverse = false; - this.$scope.roles = this.sdcConfig.roles; - this.$scope.isNewUser = false; - this.$scope.currentUser = this.userService.getLoggedinUser(); this.getAllUsers(); - let userInfo:IUserProperties = {}; - this.$scope.newUser = new User(userInfo); - this.$scope.sort = (sortBy:string):void => {//default sort by descending last update. default for alphabetical = ascending - this.$scope.isNewUser = false; this.$scope.reverse = (this.$scope.sortBy === sortBy) ? ( !this.$scope.reverse) : this.$scope.reverse = false; this.$scope.sortBy = sortBy; }; - this.$scope.createUser = ():void => { - - let onError = (response) => { - this.$scope.isLoading = false; - console.info('onFaild', response); - }; - - let onSuccess = (response:IUserProperties) => { - this.$scope.newUser.userInfo.lastLoginTime = "0"; - this.$scope.newUser.userInfo.status = response.status; - this.updateUserFilterTerm(this.$scope.newUser.userInfo); - this.$scope.usersList.push(this.$scope.newUser.userInfo); - this.$scope.isNewUser = true; - this.$scope.sortBy = null; - this.$scope.reverse = true; - this.$scope.isLoading = false; - this.$scope.newUser = new User(null); - this.$scope.editForm.$setPristine(); - let _self = this; - setTimeout(function () { - _self.$scope.isNewUser = false; - }, 7000); - }; - this.userService.createUser({ - userId: this.$scope.newUser.userInfo.userId, - role: this.$scope.newUser.userInfo.role - }).subscribe(onSuccess, onError); - }; - - - this.$scope.onEditUserPressed = (user:IUserProperties):void => { - user.isInEditMode = true; - user.tempRole = user.role; - }; - - this.$scope.editUserRole = (user:IUserProperties):void => { - let roleBeforeUpdate:string = user.role; - user.role = user.tempRole; - - let onError = (response) => { - this.$scope.isLoading = false; - user.role = roleBeforeUpdate; - console.info('onFaild', response); - }; - let onSuccess = (response:any) => { - this.$scope.isLoading = false; - user.tempRole = user.role; - this.updateUserFilterTerm(user); - }; - - this.userService.editUserRole(user.userId, user.role).subscribe(onSuccess, onError); - }; - - this.$scope.saveUserChanges = (user:IUserProperties):void => { - if (user.tempRole != user.role) { - this.$scope.editUserRole(user) - } - user.isInEditMode = false; - }; - - this.$scope.deleteUser = (userId:string):void => { - - let onOk = ():void => { - this.$scope.isLoading = true; - - let onError = (response):void => { - this.$scope.isLoading = false; - console.info('onFaild', response); - }; - - let onSuccess = (response:any):void => { - _.remove(this.$scope.usersList, {userId: userId}); - this.$scope.isLoading = false; - }; - this.userService.deleteUser(userId).subscribe(onSuccess, onError); - }; - - let title:string = this.$filter('translate')("USER_MANAGEMENT_VIEW_DELETE_MODAL_TITLE"); - let message:string = this.$filter('translate')("USER_MANAGEMENT_VIEW_DELETE_MODAL_TEXT"); - this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk); - }; - this.$scope.getTitle = (role:string):string => { return role.toLowerCase().replace('governor', 'governance_Rep').replace('_', ' '); }; - this.$scope.clearForm = ():void => { - if (!this.$scope.editForm['contactId'].$viewValue && !this.$scope.editForm['role'].$viewValue) { - this.$scope.editForm.$setPristine(); - } - //if(this.$scope.editForm['contactId'].$viewValue === '' && this.$scope.editForm['role'].$viewValue){ - // this.$scope.editForm.$setPristine(); - //} - }; } } diff --git a/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view.html b/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view.html index 9322ab00aa..89fd280205 100644 --- a/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view.html +++ b/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view.html @@ -13,7 +13,6 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> -
    @@ -22,48 +21,6 @@
    -
    -
    -
    -
    - -
    -
    - - -
    - - -
    -
    -
    - -
    - -
    -
    - -
    -
    @@ -74,15 +31,13 @@
    {{header.title}}
    -
    -
    {{user.firstName || '---'}}
    @@ -91,25 +46,10 @@
    {{user.email || '---'}}
    -
    {{user.lastLoginTime == 0 ? 'Waiting' : (user.lastLoginTime | date:'MM/dd/yyyy')}}
    -
    - - -
    -
    - -
    -
    diff --git a/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management.less b/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management.less index 934faab9e7..d1528492de 100644 --- a/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management.less +++ b/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management.less @@ -4,8 +4,7 @@ label { .i_17; } - .sdc-user-management-top-bar-form-input, - .sdc-user-management-top-bar-form-select { + .sdc-user-management-top-bar-form-input { .b_9; color: @color_b; height: 28px; @@ -29,57 +28,6 @@ top: 49px; } } - .vertical-border-container { - min-width: 50px; - margin: 0px auto; - - .vertical-border { - - width: 1px; - height: 70px; - background-color: @color_e; - display: table; - margin: 0 auto; - } - } - - .sdc-user-management-top-bar-wrapper { - display: flex; - } - - .sdc-user-management-top-bar-title { - .i_17; - font-weight: bold; - } - - .sdc-user-management-top-bar-create-user-container { - - display: flex; - flex-direction: column; - position: relative; - float: right; - padding-top: 0px; - text-align: left; - width: 650px; - - label { - margin-bottom: 20px; - } - - .sdc-user-management-top-bar-form-container { - width: 233px; - margin-right: 35px; - } - - .sdc-user-management-top-bar-create-btn { - .w-sdc-btn-light-green; - height: 30px; - width: 100px; - line-height: 0px; - padding-bottom: 3px; - margin-right: 0px; - } - } } @@ -147,9 +95,6 @@ } } } - &.sdc-user-management-table-row-edit-mode { - .bg_j; - } div { border-right: 1px solid @border_color_d; @@ -176,33 +121,6 @@ } } - - .sdc-user-management-table-btn-col { - - line-height: 0px; - text-align: center; - .sdc-user-management-table-delete-btn { - background-color: transparent; - border: none; - .sprite; - .sprite.e-sdc-small-icon-delete; - opacity: 0.7; - } - .sdc-user-management-table-edit-btn { - background-color: transparent; - border: none; - .sprite; - .e-sdc-small-icon-pencil; - opacity: 0.7; - } - .sdc-user-management-table-save-btn { - background-color: transparent; - border: none; - .sprite; - .sprite.e-sdc-green-save; - } - } - } .sdc-user-management-flex-container { diff --git a/catalog-ui/src/app/view-models/catalog/catalog-view-model.ts b/catalog-ui/src/app/view-models/catalog/catalog-view-model.ts deleted file mode 100644 index 8840afd79d..0000000000 --- a/catalog-ui/src/app/view-models/catalog/catalog-view-model.ts +++ /dev/null @@ -1,680 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import * as _ from "lodash"; -import {Component, IMainCategory, IGroup, IConfigStatuses, IAppMenu, IAppConfigurtaion, IUserProperties, ISubCategory, ICategoryBase} from "app/models"; -import {EntityService, CacheService} from "app/services"; -import {ComponentFactory, ResourceType, MenuHandler, ChangeLifecycleStateHandler} from "app/utils"; -import {UserService} from "../../ng2/services/user.service"; -import {ArchiveService} from "../../ng2/services/archive.service"; -import { ICatalogSelector, CatalogSelectorTypes } from "../../models/catalogSelector"; -import {IConfigStatus} from "../../models/app-config"; - -interface Checkboxes { - componentTypes:Array; - resourceSubTypes:Array; -} - -interface CheckboxesFilter { - // Types - selectedComponentTypes:Array; - selectedResourceSubTypes:Array; - // Categories - selectedCategoriesModel:Array; - // Statuses - selectedStatuses:Array>; -} - -interface Gui { - isLoading:boolean; - onComponentSubTypesClick:Function; - onComponentTypeClick:Function; - onCategoryClick:Function; - onStatusClick:Function; - changeFilterTerm:Function; -} - -interface IFilterParams { - components: string[]; - categories: string[]; - statuses: (string)[]; - order: [string, boolean]; - term: string; - active: boolean; -} - -interface ICategoriesMap { - [key: string]: { - category: ICategoryBase, - parent: ICategoryBase - } -} - -export interface ICatalogViewModelScope extends ng.IScope { - checkboxes:Checkboxes; - checkboxesFilter:CheckboxesFilter; - gui:Gui; - - categories:Array; - confStatus:IConfigStatuses; - sdcMenu:IAppMenu; - catalogFilterdItems:Array; - expandedSection:Array; - actionStrategy:any; - user:IUserProperties; - catalogMenuItem:any; - version:string; - sortBy:string; - reverse:boolean; - vfcmtType:string; - - //this is for UI paging - numberOfItemToDisplay:number; - isAllItemDisplay:boolean; - catalogFilteredItemsNum:number; - changeLifecycleState(entity:any, state:string):void; - sectionClick (section:string):void; - order(sortBy:string):void; - getElementFoundTitle(num:number):string; - goToComponent(component:Component):void; - raiseNumberOfElementToDisplay():void; - - selectedCatalogItem: ICatalogSelector; - catalogSelectorItems: Array; - showCatalogSelector: boolean; - catalogAllItems:Array; /* fake data */ - elementFoundTitle: string; - elementTypeTitle: string; - - selectLeftSwitchItem (item: ICatalogSelector): void; -} - -export class CatalogViewModel { - static '$inject' = [ - '$scope', - '$filter', - 'Sdc.Services.EntityService', - 'sdcConfig', - 'sdcMenu', - '$state', - '$q', - 'UserServiceNg2', - 'Sdc.Services.CacheService', - 'ComponentFactory', - 'ChangeLifecycleStateHandler', - 'MenuHandler', - 'ArchiveServiceNg2' - ]; - - private defaultFilterParams:IFilterParams = { - components: [], - categories: [], - statuses: [], - order: ['lastUpdateDate', true], - term: '', - active: true - }; - private categoriesMap:ICategoriesMap; - - constructor(private $scope:ICatalogViewModelScope, - private $filter:ng.IFilterService, - private EntityService:EntityService, - private sdcConfig:IAppConfigurtaion, - private sdcMenu:IAppMenu, - private $state:ng.ui.IStateService, - private $q:ng.IQService, - private userService:UserService, - private cacheService:CacheService, - private ComponentFactory:ComponentFactory, - private ChangeLifecycleStateHandler:ChangeLifecycleStateHandler, - private MenuHandler:MenuHandler, - private ArchiveService:ArchiveService - ) { - - - this.initLeftSwitch(); - this.initScopeMembers(); - this.loadFilterParams(); - this.initCatalogData(); // Async task to get catalog from server. - this.initScopeMethods(); - } - - - private initLeftSwitch = ():void => { - this.$scope.showCatalogSelector = false; - - this.$scope.catalogSelectorItems = [ - {value: CatalogSelectorTypes.Active, title: "Active Items", header: "Active"}, - {value: CatalogSelectorTypes.Archive, title: "Archive", header: "Archived"} - ]; - // set active items is default - this.$scope.selectedCatalogItem = this.$scope.catalogSelectorItems[0]; - }; - - private initCatalogData = ():void => { - if(this.$scope.selectedCatalogItem.value === CatalogSelectorTypes.Archive){ - this.getArchiveCatalogItems(); - } else { - this.getActiveCatalogItems(); - } - }; - - private initScopeMembers = ():void => { - // Gui init - this.$scope.gui = {}; - this.$scope.numberOfItemToDisplay = 0; - this.$scope.categories = this.cacheService.get('serviceCategories').concat(this.cacheService.get('resourceCategories')).map((cat) => cat); - this.$scope.sdcMenu = this.sdcMenu; - this.$scope.confStatus = this.sdcMenu.statuses; - this.$scope.expandedSection = ["type", "category", "status"]; - this.$scope.user = this.userService.getLoggedinUser(); - this.$scope.catalogMenuItem = this.sdcMenu.catalogMenuItem; - - // Checklist init - this.$scope.checkboxes = {}; - this.$scope.checkboxes.componentTypes = ['Resource', 'Service']; - this.$scope.checkboxes.resourceSubTypes = ['VF', 'VFC', 'CR', 'PNF', 'CP', 'VL']; - this.categoriesMap = this.initCategoriesMap(); - - this.initCheckboxesFilter(); - this.$scope.version = this.cacheService.get('version'); - this.$scope.sortBy = 'lastUpdateDate'; - this.$scope.reverse = true; - - }; - - private initCheckboxesFilter() { - // Checkboxes filter init - this.$scope.checkboxesFilter = {}; - this.$scope.checkboxesFilter.selectedComponentTypes = []; - this.$scope.checkboxesFilter.selectedResourceSubTypes = []; - this.$scope.checkboxesFilter.selectedCategoriesModel = []; - this.$scope.checkboxesFilter.selectedStatuses = []; - } - - private initCategoriesMap(categoriesList?:(ICategoryBase)[], parentCategory:ICategoryBase=null): ICategoriesMap { - categoriesList = (categoriesList) ? categoriesList : this.$scope.categories; - - // Init categories map - return categoriesList.reduce((acc, cat) => { - acc[cat.uniqueId] = { - category: cat, - parent: parentCategory - }; - const catChildren = ((cat).subcategories) - ? (cat).subcategories - : (((cat).groupings) - ? (cat).groupings - : null); - if (catChildren) { - Object.assign(acc, this.initCategoriesMap(catChildren, cat)); - } - return acc; - }, {}); - } - - private initScopeMethods = ():void => { - this.$scope.selectLeftSwitchItem = (item: ICatalogSelector): void => { - - if (this.$scope.selectedCatalogItem.value !== item.value) { - this.$scope.selectedCatalogItem = item; - switch (item.value) { - case CatalogSelectorTypes.Active: - this.getActiveCatalogItems(true); - break; - - case CatalogSelectorTypes.Archive: - this.getArchiveCatalogItems(true); - break; - } - this.changeFilterParams({active: (item.value === CatalogSelectorTypes.Active)}) - } - }; - - this.$scope.sectionClick = (section: string): void => { - let index: number = this.$scope.expandedSection.indexOf(section); - if (index !== -1) { - this.$scope.expandedSection.splice(index, 1); - } else { - this.$scope.expandedSection.push(section); - } - }; - - - this.$scope.order = (sortBy: string): void => {//default sort by descending last update. default for alphabetical = ascending - this.changeFilterParams({ - order: (this.$scope.filterParams.order[0] === sortBy) - ? [sortBy, !this.$scope.filterParams.order[1]] - : [sortBy, sortBy === 'lastUpdateDate'] - }); - }; - - - this.$scope.goToComponent = (component: Component): void => { - this.$scope.gui.isLoading = true; - this.$state.go('workspace.general', {id: component.uniqueId, type: component.componentType.toLowerCase()}); - }; - - - // Will print the number of elements found in catalog - this.$scope.getNumOfElements = (num:number):string => { - if (!num || num === 0) { - return `No ${this.$scope.selectedCatalogItem.header} Elements found`; - } else if (num === 1) { - return `1 ${this.$scope.selectedCatalogItem.header} Element found`; - } else { - return num + ` ${this.$scope.selectedCatalogItem.header} Elements found`; - } - }; - - /** - * Select | unselect sub resource when resource is clicked | unclicked. - * @param type - */ - this.$scope.gui.onComponentTypeClick = (compType: string, checked?: boolean): void => { - let components = angular.copy(this.$scope.filterParams.components); - const compIdx = components.indexOf(compType); - checked = (checked !== undefined) ? checked : compIdx === -1; - if (checked && compIdx === -1) { - components.push(compType); - components = this.cleanSubsFromList(components); - } else if (!checked && compIdx !== -1) { - components.splice(compIdx, 1); - } - this.changeFilterParams({ - components: components - }); - }; - - /** - * Selecting | unselect resources when sub resource is clicked | unclicked. - */ - this.$scope.gui.onComponentSubTypesClick = (compSubType: string, compType: string, checked?: boolean): void => { - const componentSubTypesCheckboxes = this.$scope.checkboxes[compType.toLowerCase() + 'SubTypes']; - if (componentSubTypesCheckboxes) { - let components = angular.copy(this.$scope.filterParams.components); - let componentSubTypes = components.filter((st) => st.startsWith(compType + '.')); - - const compSubTypeValue = compType + '.' + compSubType; - const compSubTypeValueIdx = components.indexOf(compSubTypeValue); - checked = (checked !== undefined) ? checked : compSubTypeValueIdx === -1; - if (checked && compSubTypeValueIdx === -1) { - components.push(compSubTypeValue); - componentSubTypes.push(compSubTypeValue); - - // if all sub types are checked, then check the main component type - if (componentSubTypes.length === componentSubTypesCheckboxes.length) { - this.$scope.gui.onComponentTypeClick(compType, true); - return; - } - } else if (!checked) { - const compIdx = components.indexOf(compType); - // if sub type exists, then remove it - if (compSubTypeValueIdx !== -1) { - components.splice(compSubTypeValueIdx, 1); - } - // else, if sub type doesn't exists, but its parent main component type exists, - // then remove the main type and push all sub types except the current - else if (compIdx !== -1) { - components.splice(compIdx, 1); - componentSubTypesCheckboxes.forEach((st) => { - if (st !== compSubType) { - components.push(compType + '.' + st); - } - }); - } - } - - this.changeFilterParams({ - components - }); - } - }; - - this.$scope.gui.onCategoryClick = (category: ICategoryBase, checked?: boolean): void => { - let categories: string[] = angular.copy(this.$scope.filterParams.categories); - let parentCategory: ICategoryBase = this.categoriesMap[category.uniqueId].parent; - - // add the category to selected categories list - const categoryIdx = categories.indexOf(category.uniqueId); - checked = (checked !== undefined) ? checked : categoryIdx === -1; - if (checked && categoryIdx === -1) { - categories.push(category.uniqueId); - - // check if all parent category children are checked, then check the parent category - if (parentCategory) { - if (this.getParentCategoryChildren(parentCategory).every((ch) => categories.indexOf(ch.uniqueId) !== -1)) { - this.$scope.gui.onCategoryClick(parentCategory, true); - return; - } - } - - categories = this.cleanSubsFromList(categories); - } else if (!checked) { - // if category exists, then remove it - if (categoryIdx !== -1) { - categories.splice(categoryIdx, 1); - } - // else, if category doesn't exists, but one of its parent categories exists, - // then remove that parent category and push all its children categories except the current - else { - let prevParentCategory: ICategoryBase = category; - let additionalCategories: string[] = []; - while (parentCategory) { - // add parent category children to list for replacing the parent category (if will be found later) - additionalCategories = additionalCategories.concat( - this.getParentCategoryChildren(parentCategory) - .filter((ch) => ch.uniqueId !== prevParentCategory.uniqueId) - .map((ch) => ch.uniqueId)); - - const parentCategoryIdx = categories.indexOf(parentCategory.uniqueId); - if (parentCategoryIdx !== -1) { - categories.splice(parentCategoryIdx, 1); - categories = categories.concat(additionalCategories); - break; - } else { - prevParentCategory = parentCategory; - parentCategory = this.categoriesMap[parentCategory.uniqueId].parent; - } - } - } - } - - this.changeFilterParams({ - categories - }); - }; - - this.$scope.gui.onStatusClick = (statusKey: string, status: IConfigStatus, checked?: boolean) => { - const statuses = angular.copy(this.$scope.filterParams.statuses); - - // add the status key to selected statuses list - const statusIdx = statuses.indexOf(statusKey); - checked = (checked !== undefined) ? checked : statusIdx === -1; - if (checked && statusIdx === -1) { - statuses.push(statusKey); - } else if (!checked && statusIdx !== -1) { - statuses.splice(statusIdx, 1); - } - - this.changeFilterParams({ - statuses - }); - }; - - this.$scope.gui.changeFilterTerm = (filterTerm: string) => { - this.changeFilterParams({ - term: filterTerm - }); - }; - - this.$scope.raiseNumberOfElementToDisplay = (): void => { - this.$scope.numberOfItemToDisplay = this.$scope.numberOfItemToDisplay + 35; - if (this.$scope.catalogFilterdItems) { - this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.catalogFilterdItems.length; - } - }; - - } - - private getAllCategoryChildrenIdsFlat(category:ICategoryBase) { - let catChildrenIds = []; - if ((category).subcategories) { - catChildrenIds = (category).subcategories.reduce((acc, scat) => { - return acc.concat(this.getAllCategoryChildrenIdsFlat(scat)); - }, (category).subcategories.map((scat) => scat.uniqueId)); - } - else if ((category).groupings) { - catChildrenIds = (category).groupings.map((g) => g.uniqueId); - } - return catChildrenIds; - } - - private getParentCategoryChildren(parentCategory:ICategoryBase): ICategoryBase[] { - if ((parentCategory).subcategories) { - return (parentCategory).subcategories; - } else if ((parentCategory).groupings) { - return (parentCategory).groupings; - } - return []; - } - - private cleanSubsFromList(list:Array, delimiter:string='.', removeSubsList?:Array) { - let curRemoveSubsList = (removeSubsList || list).slice().sort(); // by default remove any children of any item in list - while (curRemoveSubsList.length) { - const curRemoveSubItem = curRemoveSubsList.shift(); - const removeSubListFilter = (x) => !x.startsWith(curRemoveSubItem + delimiter); - list = list.filter(removeSubListFilter); - curRemoveSubsList = curRemoveSubsList.filter(removeSubListFilter); - } - return list; - } - - private applyFilterParamsToView(filterParams:IFilterParams) { - // reset checkboxes filter - this.initCheckboxesFilter(); - - this.applyFilterParamsComponents(filterParams); - this.applyFilterParamsCategories(filterParams); - this.applyFilterParamsStatuses(filterParams); - this.applyFilterParamsOrder(filterParams); - this.applyFilterParamsTerm(filterParams); - } - - private applyFilterParamsComponents(filterParams:IFilterParams) { - const componentList = []; - const componentSubTypesLists = {}; - filterParams.components.forEach((compStr) => { - const compWithSub = compStr.split('.', 2); - const mainComp = compWithSub[0]; - const subComp = compWithSub[1]; - if (!subComp) { // main component type - componentList.push(mainComp); - - // if component type has sub types list, then add all component sub types - const checkboxesSubTypeKey = mainComp.toLowerCase() + 'SubTypes'; - if (this.$scope.checkboxes.hasOwnProperty(checkboxesSubTypeKey)) { - componentSubTypesLists[mainComp] = angular.copy(this.$scope.checkboxes[checkboxesSubTypeKey]); - } - } else { // sub component type - // init component sub types list - if (!componentSubTypesLists.hasOwnProperty(mainComp)) { - componentSubTypesLists[mainComp] = []; - } - // add sub type to list if not exist - if (componentSubTypesLists[mainComp].indexOf(subComp) === -1) { - componentSubTypesLists[mainComp].push(subComp); - } - } - }); - this.$scope.checkboxesFilter.selectedComponentTypes = componentList; - Object.keys(componentSubTypesLists).forEach((tKey) => { - const compSelectedSubTypeKey = 'selected' + tKey + 'SubTypes'; - if (this.$scope.checkboxesFilter.hasOwnProperty(compSelectedSubTypeKey)) { - this.$scope.checkboxesFilter[compSelectedSubTypeKey] = componentSubTypesLists[tKey]; - } - }); - - let selectedCatalogIndex = filterParams.active ? CatalogSelectorTypes.Active : CatalogSelectorTypes.Archive; - this.$scope.selectedCatalogItem = this.$scope.catalogSelectorItems[selectedCatalogIndex]; - - } - - private applyFilterParamsCategories(filterParams:IFilterParams) { - this.$scope.checkboxesFilter.selectedCategoriesModel = filterParams.categories.reduce((acc, c) => { - acc.push(c); - const cat = this.categoriesMap[c].category; - if (cat) { - acc = acc.concat(this.getAllCategoryChildrenIdsFlat(cat)); - } - return acc; - }, []); - } - - private getActiveCatalogItems(forceReload?: boolean): void { - - if (forceReload || this.componentShouldReload()) { - this.$scope.gui.isLoading = true; - let onSuccess = (followedResponse:Array):void => { - this.updateCatalogItems(followedResponse); - this.$scope.gui.isLoading = false; - this.cacheService.set('breadcrumbsComponentsState', this.$state.current.name); //catalog - this.cacheService.set('breadcrumbsComponents', followedResponse); - }; - - let onError = ():void => { - console.info('Failed to load catalog CatalogViewModel::getActiveCatalogItems'); - this.$scope.gui.isLoading = false; - }; - this.EntityService.getCatalog().then(onSuccess, onError); - } else { - let cachedComponents = this.cacheService.get('breadcrumbsComponents'); - this.updateCatalogItems(cachedComponents); - } - } - - private getArchiveCatalogItems(forceReload?: boolean): void { - if(forceReload || !this.cacheService.contains("archiveComponents")) { - this.$scope.gui.isLoading = true; - let onSuccess = (followedResponse:Array):void => { - this.cacheService.set("archiveComponents", followedResponse); - this.updateCatalogItems(followedResponse); - this.$scope.gui.isLoading = false; - }; - - let onError = ():void => { - console.info('Failed to load catalog CatalogViewModel::getArchiveCatalogItems'); - this.$scope.gui.isLoading = false; - }; - - this.ArchiveService.getArchiveCatalog().subscribe(onSuccess, onError); - } else { - let archiveCache = this.cacheService.get("archiveComponents"); - this.updateCatalogItems(archiveCache); - } - - } - - private updateCatalogItems = (items:Array):void => { - this.$scope.catalogFilterdItems = items; - this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.catalogFilterdItems.length; - this.$scope.categories = this.cacheService.get('serviceCategories').concat(this.cacheService.get('resourceCategories')); - } - - private componentShouldReload = ():boolean => { - let breadcrumbsValid: boolean = (this.$state.current.name === this.cacheService.get('breadcrumbsComponentsState') && this.cacheService.contains('breadcrumbsComponents')); - return !breadcrumbsValid || this.isDefaultFilter(); - } - - private isDefaultFilter = (): boolean => { - return angular.equals(this.defaultFilterParams, this.$scope.filterParams); - } - - private applyFilterParamsStatuses(filterParams: IFilterParams) { - this.$scope.checkboxesFilter.selectedStatuses = filterParams.statuses.reduce((acc, stKey:string) => { - const status = this.$scope.confStatus[stKey]; - if (status) { - acc.push(status.values); - } - return acc; - }, []); - } - - private applyFilterParamsOrder(filterParams: IFilterParams) { - this.$scope.sortBy = filterParams.order[0]; - this.$scope.reverse = filterParams.order[1]; - } - - private applyFilterParamsTerm(filterParams: IFilterParams) { - this.$scope.search = { - filterTerm: filterParams.term - }; - } - - private loadFilterParams() { - const params = this.$state.params; - this.$scope.filterParams = angular.copy(this.defaultFilterParams); - Object.keys(params).forEach((k) => { - if (!angular.isUndefined(params[k])) { - let newVal; - let filterKey = k.substr('filter.'.length); - switch (k) { - case 'filter.components': - case 'filter.categories': - newVal = _.uniq(params[k].split(',')); - newVal = this.cleanSubsFromList(newVal); - break; - case 'filter.statuses': - newVal = _.uniq(params[k].split(',')); - break; - case 'filter.order': - newVal = params[k].startsWith('-') ? [params[k].substr(1), true] : [params[k], false]; - break; - case 'filter.term': - newVal = params[k]; - break; - case 'filter.active': - newVal = (params[k] === "true" || params[k] === true); - break; - default: - // unknown filter key - filterKey = null; - } - if (filterKey) { - this.$scope.filterParams[filterKey] = newVal; - } - } - }); - // re-set filter params with valid values - this.applyFilterParamsToView(this.$scope.filterParams); - - } - - private changeFilterParams(changedFilterParams) { - const newParams = {}; - Object.keys(changedFilterParams).forEach((k) => { - let newVal; - switch (k) { - case 'components': - case 'categories': - case 'statuses': - newVal = changedFilterParams[k] && changedFilterParams[k].length ? changedFilterParams[k].join(',') : null; - break; - case 'order': - newVal = (changedFilterParams[k][1] ? '-' : '') + changedFilterParams[k][0]; - break; - case 'term': - newVal = changedFilterParams[k] ? changedFilterParams[k] : null; - break; - case 'active': - newVal = changedFilterParams[k]; - break; - default: - return; - } - this.$scope.filterParams[k] = changedFilterParams[k]; - newParams['filter.' + k] = newVal; - }); - this.$state.go('.', newParams, {location: 'replace', notify: false}).then(() => { - this.applyFilterParamsToView(this.$scope.filterParams); - }); - } -} diff --git a/catalog-ui/src/app/view-models/catalog/catalog-view.html b/catalog-ui/src/app/view-models/catalog/catalog-view.html deleted file mode 100644 index 25fa561155..0000000000 --- a/catalog-ui/src/app/view-models/catalog/catalog-view.html +++ /dev/null @@ -1,209 +0,0 @@ - - -
    - - - - -
    - -
    -
    - {{selectedCatalogItem.title}} -
    -
     
    - -
    -
    - {{leftSwitchItem.title}} -
    -
    -
    - - - -
    -
    -
    - - Type -
    -
    -
      -
    • - - - -
        -
      • - - - -
      • -
      -
    • -
    -
    -
    - -
    -
    - - Categories -
    -
    - -
      -
    • - - - - -
        -
      • - - - - -
          -
        • - - - -
        • -
        -
      • -
      -
    • -
    - -
    -
    - - -
    -
    - - Status -
    - -
    -
      - - -
    • - - - -
      -
    • -
    -
    -
    - -
    -
    - - - - - -
    -
    -
    -    -   - -  |  -   - -
    -
    - -
    - -
    - - - - - -
    - -
    -
    - -
    - - - - -
    diff --git a/catalog-ui/src/app/view-models/catalog/catalog.less b/catalog-ui/src/app/view-models/catalog/catalog.less deleted file mode 100644 index 45556030e3..0000000000 --- a/catalog-ui/src/app/view-models/catalog/catalog.less +++ /dev/null @@ -1,362 +0,0 @@ -.sdc-catalog-container { - - .i-sdc-categories-list-item { - font-weight: normal; - } - - // Checkboxes - .i-sdc-designer-leftbar-section-content-ul { - padding: 0; - margin: 0; - - .i-sdc-designer-leftbar-section-content-ul-li { - margin-top: 5px; - - .tlv-checkbox { - font-size: 13px; - font-family: @font-opensans-medium; - color: @func_color_s; - } - } - - .i-sdc-catalog-subcategories-checkbox { - padding: 0 0 0 20px; - margin: 0; - - > li { - margin-top: 5px; - - .tlv-checkbox { - font-size:13px; - font-family: @font-opensans-regular; - } - } - - .i-sdc-catalog-grouping-checkbox { - padding: 0 0 0 20px; - margin: 0; - } - - } - - } - - .i-sdc-designer-leftbar-section-content-li { - &:last-child { - .i-sdc-categories-list-item { - margin: 0; - } - } - } - - .i-sdc-categories-list-item { - display: block; - //margin-bottom: 5px; - //padding-left: 15px; - //text-indent: -24px; - vertical-align: top; - font-weight: bold; - } - - .i-sdc-subcategories-list-item { - display: block; - //padding-left: 20px; - vertical-align: top; - font-weight: normal; - margin: 0; - //text-indent: -10px; - } - - .i-sdc-categories-list-item-icon { - display: inline-block; - float: right; - position: relative; - right: -8px; - top: 6px; - } - - .i-sdc-categories-list-item { - margin-top: 7px; - &.NOT_CERTIFIED_CHECKOUT, - &.NOT_CERTIFIED_CHECKIN { - .i-sdc-categories-list-item-icon { - background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -2889px; - width: 14px; - height: 14px; - - } - } - - &.CERTIFIED { - .i-sdc-categories-list-item-icon { - background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -3034px; - width: 14px; - height: 16px; - } - } - - &.READY_FOR_CERTIFICATION { - .i-sdc-categories-list-item-icon { - background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -2985px; - width: 14px; - height: 16px; - } - } - - &.CERTIFICATION_IN_PROGRESS { - .i-sdc-categories-list-item-icon { - background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -2934px; - width: 14px; - height: 16px; - } - } - - &.DISTRIBUTED, - &.TBD { - .i-sdc-categories-list-item-icon { - background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -43px -3087px; - width: 24px; - height: 14px; - - } - } - } - - .i-sdc-categories-list-input { - margin: 8px; - - } - - .i-sdc-subcategories-list-input { - - margin: 8px; - } - .i-sdc-subcategories-list-input-container { - margin: 0px 0px 0px 20px; - padding: 2px; - } - - .w-sdc-header-catalog-search-container { - display: table; - padding: 21px 0; - position: relative; - - .w-sdc-designer-leftbar-search-input { - color: #000; - width: 300px; - } - } - - .w-sdc-catalog-main { - padding: 10px 12px; - } - .w-sdc-dashboard-catalog-items-header { - .b_3; - color: @main_color_m; - font-family: OpenSans-Regular, sans-serif; - font-size: 14px; - display: inline-block; - font-style: normal; - margin-left: 11px; - b { - font-family: OpenSans-Bold, sans-serif; - color: @main_color_l; - font-weight: bold; - } - font-weight: normal; - /* padding-left: 10px; */ - } - - .w-sdc-dashboard-catalog-header-order1 { - .b_3; - font-weight: 800; - } - - .w-sdc-dashboard-catalog-sort { - .b_3; - font-weight: bold; - white-space:pre; - &:hover{ - .hand; - text-decoration: none; - .a_3; - } - &.blue { - .a_3; - } - } - - .w-sdc-catalog-sort-arrow{ - display: inline-block; - &.up{ - .b_3; - width: 0; - height: 0; - border-left: 5px solid transparent; - border-right: 5px solid transparent; - border-bottom: 5px solid ; - } - &.down{ - .b_3; - width: 0; - height: 0; - border-left: 5px solid transparent; - border-right: 5px solid transparent; - border-top: 5px solid; - } - } - - - .w-sdc-dashboard-catalog-header-right{ - float: right; - display: inline-block; - padding-right:34px; - } - - .w-sdc-header-catalog-search-input { - width: 420px; - display: table-cell; - padding: 0 25px 1px 10px; - border: 1px solid #bcbcbc; - .border-radius(10px); - height: 30px; - margin: 10px 30px; - outline: none; - } - - .sdc-catalog-type-filter-container { - margin-top: -1px; - } - - .i-sdc-designer-leftbar-section-title { - text-transform: uppercase; - .l_14_m; - line-height: 30px; - } - - .i-sdc-designer-leftbar-section-title-icon { - .hand; - .tlv-sprite; - .footer-close; - transition: .3s all; - margin-top: -4px; - } - - .i-sdc-designer-leftbar-section-title-text { - margin-left: 20px; - } - - /* added Michael */ - .i-sdc-designer-left-sidebar { - margin-top: 43px; - } - .i-sdc-designer-leftbar-section-left-switch-header { - text-transform: uppercase; - .l_14_m; - line-height: 40px; - width: 243px; - - font-family: OpenSans-Bold, sans-serif; - font-size: 14px; - - color: @main_color_a; - background-color: @tlv_color_t; - border: solid 1px fade(@main_color_t, 40%); - cursor: pointer; - opacity: 1; - z-index: 9999; - position: relative; - //box-shadow: 1px 0 2px #00000036; - } - .i-sdc-designer-leftbar-section-left-switch-header-text { - display: inline-block; - width: 180px; - margin-left: 20px; - } - .i-sdc-designer-leftbar-section-left-switch-header-icon { - display: inline-block; - vertical-align: middle; - } - - - .seperator-left, - .seperator-right { - border-right: solid 1px @color_m; - display: table-cell; - width: 2px; - } - - // Rotate catalog left side arrows - .i-sdc-designer-leftbar-section-title.expanded .i-sdc-designer-leftbar-section-title-icon { - transform: rotate(180deg); - } - - // Transform catalog left side sections - .i-sdc-designer-leftbar-section-title + .i-sdc-designer-leftbar-section-content { - max-height: 0px; - margin: 0 auto; - transition: all .3s; - overflow: hidden; - padding: 0 10px 0 18px; - } - - .i-sdc-designer-leftbar-section-title.expanded + .i-sdc-designer-leftbar-section-content { - max-height: 9999px; - margin: 0 auto 1px; - transition: all .3s; - padding: 10px 18px 10px 18px; - overflow: hidden; - } - -} - -.w-sdc-search-icon{ - position: absolute; - right: 40px; - top: 40px; - &.leftbar{ - top: 19px; - right: 18px; - } - &.magnification { - .sprite; - .sprite.magnification-glass; - .hand; - } - - &.cancel { - .sprite; - .sprite.clear-text; - .hand; - } -} - -/* added Michael */ -.sdc-catalog-selector-wrapper { - position: absolute; - left: 0px; - top: 42px; - width: 241px; - height: auto; - cursor: pointer; - opacity: 1; - z-index: 1000; - box-shadow: 1px 2px 3px #b1b1b1; -} - -.sdc-catalog-selector-item { - text-transform: none; - line-height: 40px; - font-family: OpenSans-Bold, sans-serif; - font-size: 14px; - color: @main_color_l; - background-color: @main_color_p; - padding-left: 20px; -} - -.sdc-catalog-selector-item:hover { - color: @main_color_a; - background-color: @tlv_color_v; -} - - diff --git a/catalog-ui/src/app/view-models/dashboard/dashboard-view-model.ts b/catalog-ui/src/app/view-models/dashboard/dashboard-view-model.ts deleted file mode 100644 index 4d084045f7..0000000000 --- a/catalog-ui/src/app/view-models/dashboard/dashboard-view-model.ts +++ /dev/null @@ -1,497 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {IConfigRoles, IAppConfigurtaion, IAppMenu, IUserProperties, Component} from "app/models"; -import {EntityService, SharingService, CacheService} from "app/services"; -import {ComponentType, ResourceType, MenuHandler, ModalsHandler, ChangeLifecycleStateHandler, SEVERITY, ComponentFactory, CHANGE_COMPONENT_CSAR_VERSION_FLAG} from "app/utils"; -import {IClientMessageModalModel} from "../modals/message-modal/message-client-modal/client-message-modal-view-model"; -import {UserService} from "../../ng2/services/user.service"; - - -export interface IDashboardViewModelScope extends ng.IScope { - - isLoading:boolean; - numberOfItemToDisplay:number; - components:Array; - folders:FoldersMenu; - roles:IConfigRoles; - user:IUserProperties; - sdcConfig:IAppConfigurtaion; - sdcMenu:IAppMenu; - sharingService:SharingService; - showTutorial:boolean; - isFirstTime:boolean; - version:string; - filterParams:DashboardFilter; - vfcmtType:string; - - changeFilterParams():void; - updateSearchTerm(newTerm:string):void; - onImportVfc(file:any):void; - onImportVf(file:any):void; - openCreateModal(componentType:ComponentType, importedFile:any):void; - openWhatsNewModal(version:string):void; - openDesignerModal(isResource:boolean, uniqueId:string):void; - setSelectedFolder(folderItem:FoldersItemsMenu):void; - entitiesCount(folderItem:FoldersItemsMenu):number; - getCurrentFolderDistributed():Array; - changeLifecycleState(entity:any, data:any):void; - goToComponent(component:Component):void; - raiseNumberOfElementToDisplay():void; - wizardDebugEdit:Function; - notificationIconCallback:Function; -} - -interface ICheckboxesFilter { - // Statuses - selectedStatuses:Array; - // distributed - distributed:Array; -} - -export interface IItemMenu { - -} - -export interface IMenuItemProperties { - text:string; - group:string; - state:string; - dist:string; - groupname:string; - states:Array; -} - -export interface IQueryFilterParams { - 'filter.term': string; - 'filter.distributed': string; - 'filter.status': string -} - - -export class DashboardFilter { - searchTerm: string; - checkboxes: ICheckboxesFilter; - - constructor(params = {}) { - this.searchTerm = params['filter.term'] || ""; - this.checkboxes = { - selectedStatuses : params['filter.status']? params['filter.status'].split(',') : [], - distributed : params['filter.distributed']? params['filter.distributed'].split(',') : [] - }; - } - - public toParam = ():IQueryFilterParams => { - return { - 'filter.term': this.searchTerm, - 'filter.distributed': this.checkboxes && this.checkboxes.distributed.join(',') || null, - 'filter.status': this.checkboxes && this.checkboxes.selectedStatuses.join(',') || null - }; - } - -} - -export class FoldersMenu { - - private _folders:Array = []; - - constructor(folders:Array) { - let self = this; - folders.forEach(function (folder:IMenuItemProperties) { - if (folder.groupname) { - self._folders.push(new FoldersItemsMenuGroup(folder)); - } else { - self._folders.push(new FoldersItemsMenu(folder)); - } - }); - self._folders[0].setSelected(true); - } - - public getFolders = ():Array => { - return this._folders; - }; - - public getCurrentFolder = ():FoldersItemsMenu => { - let menuItem:FoldersItemsMenu = undefined; - this.getFolders().forEach(function (tmpFolder:FoldersItemsMenu) { - if (tmpFolder.isSelected()) { - menuItem = tmpFolder; - } - }); - return menuItem; - }; - - public setSelected = (folder:FoldersItemsMenu):void => { - this.getFolders().forEach(function (tmpFolder:FoldersItemsMenu) { - tmpFolder.setSelected(false); - }); - folder.setSelected(true); - } - -} - -export class FoldersItemsMenu implements IItemMenu { - - public text:string; - public group:string; - public state:string; - public dist:string; - public states:Array; - - private selected:boolean = false; - - constructor(menuProperties:IMenuItemProperties) { - this.text = menuProperties.text; - this.group = menuProperties.group; - this.state = menuProperties.state; - this.states = menuProperties.states; - this.dist = menuProperties.dist; - } - - public isSelected = ():boolean => { - return this.selected; - }; - - public setSelected = (value:boolean):void => { - this.selected = value; - }; - - public isGroup = ():boolean => { - return false; - } - -} - -export class FoldersItemsMenuGroup extends FoldersItemsMenu { - - public groupname:string; - - constructor(menuProperties:IMenuItemProperties) { - super(menuProperties); - this.groupname = menuProperties.groupname; - } - - public isGroup = ():boolean => { - return true; - } - -} - -export class DashboardViewModel { - static '$inject' = [ - '$scope', - '$filter', - 'Sdc.Services.EntityService', - '$http', - 'sdcConfig', - 'sdcMenu', - '$state', - '$stateParams', - 'UserServiceNg2', - 'Sdc.Services.SharingService', - 'Sdc.Services.CacheService', - '$q', - 'ComponentFactory', - 'ChangeLifecycleStateHandler', - 'ModalsHandler', - 'MenuHandler' - ]; - - private components:Array; - - constructor(private $scope:IDashboardViewModelScope, - private $filter:ng.IFilterService, - private entityService:EntityService, - private $http:ng.IHttpService, - private sdcConfig:IAppConfigurtaion, - private sdcMenu:IAppMenu, - private $state:ng.ui.IStateService, - private $stateParams:any, - private userService:UserService, - private sharingService:SharingService, - private cacheService:CacheService, - private $q:ng.IQService, - private ComponentFactory:ComponentFactory, - private ChangeLifecycleStateHandler:ChangeLifecycleStateHandler, - private ModalsHandler:ModalsHandler, - private MenuHandler:MenuHandler) { - this.initScope(); - this.initFolders(); - this.initEntities(); - - if (this.$stateParams) { - - if (this.$state.params.folder) { - let self = this; - let folderName = this.$state.params.folder.replaceAll("_", " "); - - this.$scope.folders.getFolders().forEach(function (tmpFolder:FoldersItemsMenu) { - if (tmpFolder.text === folderName) { - self.$scope.setSelectedFolder(tmpFolder); - } - }); - } - - // Show the tutorial if needed when the dashboard page is opened. - // This is called from the welcome page. - else if (this.$stateParams.show === 'tutorial') { - this.$scope.showTutorial = true; - this.$scope.isFirstTime = true; - } - } - } - - private initFolders = ():void => { - if (this.$scope.user) { - this.$scope.folders = new FoldersMenu(this.$scope.roles[this.$scope.user.role].folder); - } - }; - - private initScope = ():void => { - let self = this; - - this.$scope.version = this.cacheService.get('version'); - this.$scope.sharingService = this.sharingService; - this.$scope.numberOfItemToDisplay = 0; - this.$scope.isLoading = false; - this.$scope.sdcConfig = this.sdcConfig; - this.$scope.sdcMenu = this.sdcMenu; - this.$scope.user = this.userService.getLoggedinUser(); - this.$scope.roles = this.sdcMenu.roles; - this.$scope.showTutorial = false; - this.$scope.isFirstTime = false; - this.$scope.vfcmtType = ResourceType.VFCMT; - this.$scope.filterParams = new DashboardFilter(this.$state.params); - - // Open onboarding modal - this.$scope.notificationIconCallback = ():void => { - this.ModalsHandler.openOnboadrdingModal('Import').then((result)=> { - //OK - if(!result.previousComponent || result.previousComponent.csarVersion != result.componentCsar.csarVersion) { - this.cacheService.set(CHANGE_COMPONENT_CSAR_VERSION_FLAG, result.componentCsar.csarVersion); - } - - this.$state.go('workspace.general', { - id: result.previousComponent && result.previousComponent.uniqueId, - componentCsar: result.componentCsar, - type: result.type - }); - }, ()=> { - // ERROR - }); - }; - - this.$scope.onImportVf = (file:any):void => { - if (file && file.filename) { - // Check that the file has valid extension. - let fileExtension:string = file.filename.split(".").pop(); - if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) { - this.$state.go('workspace.general', { - type: ComponentType.RESOURCE.toLowerCase(), - importedFile: file, - resourceType: ResourceType.VF - }); - } else { - let data:IClientMessageModalModel = { - title: self.$filter('translate')("NEW_SERVICE_RESOURCE_ERROR_VALID_CSAR_EXTENSIONS_TITLE"), - message: self.$filter('translate')("NEW_SERVICE_RESOURCE_ERROR_VALID_CSAR_EXTENSIONS", "{'extensions': '" + this.sdcConfig.csarFileExtension + "'}"), - severity: SEVERITY.ERROR - }; - this.ModalsHandler.openClientMessageModal(data); - } - } - }; - - this.$scope.onImportVfc = (file:any):void => { - if (file && file.filename) { - // Check that the file has valid extension. - let fileExtension:string = file.filename.split(".").pop(); - if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) { - this.$state.go('workspace.general', { - type: ComponentType.RESOURCE.toLowerCase(), - importedFile: file, - resourceType: ResourceType.VFC - }); - } else { - let data:IClientMessageModalModel = { - title: self.$filter('translate')("NEW_SERVICE_RESOURCE_ERROR_VALID_TOSCA_EXTENSIONS_TITLE"), - message: self.$filter('translate')("NEW_SERVICE_RESOURCE_ERROR_VALID_TOSCA_EXTENSIONS", "{'extensions': '" + this.sdcConfig.toscaFileExtension + "'}"), - severity: SEVERITY.ERROR - }; - this.ModalsHandler.openClientMessageModal(data); - } - } - }; - - this.$scope.openCreateModal = (componentType:string, importedFile:any):void => { - if (importedFile) { - this.initEntities(true); // Return from import - } else { - this.$state.go('workspace.general', {type: componentType.toLowerCase()}); - } - - }; - - this.$scope.createPNF = ():void => { - this.$state.go('workspace.general', { - type: ComponentType.RESOURCE.toLowerCase(), - resourceType: ResourceType.PNF - }); - }; - - this.$scope.createCR = ():void => { - this.$state.go('workspace.general', { - type: ComponentType.RESOURCE.toLowerCase(), - resourceType: ResourceType.CR - }); - }; - - this.$scope.entitiesCount = (folderItem:FoldersItemsMenu):any => { - let self = this; - let total:number = 0; - if (folderItem.isGroup()) { - this.$scope.folders.getFolders().forEach(function (tmpFolder:FoldersItemsMenu) { - if (tmpFolder.group && tmpFolder.group === (folderItem).groupname) { - total = total + self._getTotalCounts(tmpFolder, self); - } - }); - } else { - total = total + self._getTotalCounts(folderItem, self); - } - return total; - }; - - this.$scope.getCurrentFolderDistributed = ():Array => { - let self = this; - let states = []; - if (this.$scope.folders) { - let folderItem:FoldersItemsMenu = this.$scope.folders.getCurrentFolder(); - if (folderItem.isGroup()) { - this.$scope.folders.getFolders().forEach(function (tmpFolder:FoldersItemsMenu) { - if (tmpFolder.group && tmpFolder.group === (folderItem).groupname) { - self._setStates(tmpFolder, states); - } - }); - } else { - self._setStates(folderItem, states); - } - } - return states; - }; - - this.$scope.setSelectedFolder = (folderItem:FoldersItemsMenu):void => { - this.$scope.folders.setSelected(folderItem); - }; - - this.$scope.goToComponent = (component:Component):void => { - this.$scope.isLoading = true; - this.$state.go('workspace.general', {id: component.uniqueId, type: component.componentType.toLowerCase()}); - }; - - this.$scope.raiseNumberOfElementToDisplay = ():void => { - this.$scope.numberOfItemToDisplay = this.$scope.numberOfItemToDisplay + 35; - if (this.$scope.components) { - this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.components.length; - } - }; - - this.$scope.updateSearchTerm = (newTerm: string):void => { - this.$scope.filterParams.searchTerm = newTerm; - }; - - this.$scope.changeFilterParams = ():void => { - this.$state.go('.', this.$scope.filterParams.toParam(), {location: 'replace', notify: false}); - }; - }; - - private _getTotalCounts(tmpFolder, self):number { - let total:number = 0; - if (tmpFolder.dist !== undefined) { - let distributions = tmpFolder.dist.split(','); - distributions.forEach((item:any) => { - total = total + self.getEntitiesByStateDist(tmpFolder.state, item).length; - }); - } - else { - total = total + self.getEntitiesByStateDist(tmpFolder.state, tmpFolder.dist).length; - } - return total; - } - - private _setStates(tmpFolder, states) { - if (tmpFolder.states !== undefined) { - tmpFolder.states.forEach(function (item:any) { - states.push({"state": item.state, "dist": item.dist}); - }); - } else { - states.push({"state": tmpFolder.state, "dist": tmpFolder.dist}); - } - } - - private initEntities = (forceReload?:boolean):void => { - - if(forceReload || this.componentShouldReload()){ - this.$scope.isLoading = true; - this.entityService.getAllComponents(true).then( - (components:Array) => { - this.cacheService.set('breadcrumbsComponentsState', this.$state.current.name); //dashboard - this.cacheService.set('breadcrumbsComponents', components); - this.components = components; - this.$scope.components = components; - this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.components.length; - this.$scope.isLoading = false; - }); - } else { - this.components = this.cacheService.get('breadcrumbsComponents'); - this.$scope.components = this.components; - this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.components.length; - - } - - }; - - private isDefaultFilter = (): boolean => { - let defaultFilter = new DashboardFilter(); - return angular.equals(defaultFilter, this.$scope.filterParams); - } - - private componentShouldReload = ():boolean => { - let breadcrumbsValid: boolean = (this.$state.current.name === this.cacheService.get('breadcrumbsComponentsState') && this.cacheService.contains('breadcrumbsComponents')); - return !breadcrumbsValid || this.isDefaultFilter(); - } - - private getEntitiesByStateDist = (state:string, dist:string):Array => { - let gObj:Array; - if (this.components && (state || dist)) { - gObj = this.components.filter(function (obj:Component) { - if (dist !== undefined && obj.distributionStatus === dist && obj.lifecycleState === state) { - return true; - } else if (dist === undefined && obj.lifecycleState === state) { - return true; - } - return false; - }); - } else { - gObj = []; - } - return gObj; - } -} diff --git a/catalog-ui/src/app/view-models/dashboard/dashboard-view.html b/catalog-ui/src/app/view-models/dashboard/dashboard-view.html deleted file mode 100644 index 240a74d292..0000000000 --- a/catalog-ui/src/app/view-models/dashboard/dashboard-view.html +++ /dev/null @@ -1,109 +0,0 @@ - - -
    - - - - -
    - - - -
    - -
    - - -
    -
    -
    -
    - - - - -
    -
    -
    - - -
    -
    -
    -
    -
    Import VFC - -
    -
    Import VSP
    -
    Import DCAE asset - -
    -
    -
    -
    - - - - - -
    - -
    - -
    - -
    -
    - {{folder.text}} - - - - - {{entitiesCount(folder)}} -
    -
    - -
    - - - -
    -
    - - diff --git a/catalog-ui/src/app/view-models/dashboard/dashboard.less b/catalog-ui/src/app/view-models/dashboard/dashboard.less deleted file mode 100644 index 02280cdb42..0000000000 --- a/catalog-ui/src/app/view-models/dashboard/dashboard.less +++ /dev/null @@ -1,413 +0,0 @@ -.sdc-dashboard-container { - .tlv-loader { - top: -110px; - left: 80px; - } - .sdc-hide-popover { - .popover { - display: none !important; - } - } -} - -.w-sdc-left-sidebar-nav { - margin-top: 46px; -} - -.w-sdc-main-right-container-element { - float: left; - height: 217px; - width: 217px; - margin: 10px; - position: relative; -} - -.w-sdc-main-right-container-element-details-container { - position: absolute; - top: 165px; - left: 50px; -} - -.w-sdc-main-right-container-element-name { - font-weight: bold; -} - -.w-sdc-main-right-container-element-owner { - -} - -//////////////////////////////Cards//////////////////// -.w-sdc-dashboard-card-new { - border: 2px dashed @color_m; - .border-radius(2px); - cursor: pointer; - display: inline-block; - height: 198px; - margin: 11px; - position: relative; - vertical-align: middle; - width: 202px; -} - -.w-sdc-dashboard-card-new-content { - display: flex; - justify-content: center; - align-items: center; - flex-direction: column; - height: 100%; -} - -.w-sdc-dashboard-card-new-content-plus { - .sprite-new; - .add-icon; - position: relative; - margin-bottom: 20px; - - &:after { - .n_14_m; - content: 'ADD'; - position: absolute; - top: 25px; - left: -3px; - vertical-align: -50%; - } -} - -.w-sdc-dashboard-card-import-content-plus { - .sprite-new; - .import-icon; - position: relative; - margin-bottom: 20px; - - &:after { - .n_14_m; - content: 'IMPORT'; - position: absolute; - top: 25px; - left: -16px; - vertical-align: -50%; - } -} - -.sdc-dashboard-create-element-container, -.sdc-dashboard-import-element-container { - - width: 140px; - - .tlv-btn.import-dcae { - padding: 0; - } - - .tlv-btn { - position: relative; - width: 100%; - margin-bottom: 10px; - - &:last-child { - margin-bottom: 0; - } - } - - input[type="file"] { - cursor: inherit; - filter: alpha(opacity=0); - opacity: 0; - position: absolute; - top: 0; - left: 0; - width: 138px; - height: 30px; - } -} - -.w-sdc-dashboard-card { - width: 204px; - height: 200px; - background-color: @main_color_p; - .border-radius(2px); - .box-shadow(0px 2px 2px 0px rgba(24, 24, 25, 0.05)); - display: inline-block; - margin: 10px; - position: relative; - vertical-align: middle; - border: solid 1px @main_color_p; - - &:hover { - border: solid 1px @main_color_o; - .box-shadow(3px 3px 2px 0px rgba(24, 24, 25, 0.05)); - } - - &:active { - border: solid 1px @main_color_c; - .box-shadow(3px 3px 2px 0px rgba(24, 24, 25, 0.05)); - } -} - -.w-sdc-dashboard-card-body { - .hand; - border-bottom: 1px solid @color_j; - height: 155px; - position: relative; - text-align: center; -} - -.w-sdc-dashboard-card-description { - .c_3; - .hand; - background-color: rgba(57, 73, 84, 0.9); - border-radius: 4px 4px 0 0; - bottom: 0; - left: 0; - opacity: 0; - padding: 10px; - position: absolute; - right: 0; - text-align: left; - top: 0; - word-wrap: break-word; - z-index: 4; - min-height: 100px; - overflow: hidden; -} - - -.w-sdc-dashboard-card-schema { - margin-top: 30px; -} - -.w-sdc-dashboard-card-edit { - .hand; - position: absolute; - right: 13px; - top: 15px; - z-index: 2; -} - -.w-sdc-dashboard-card-footer { - padding: 3px 12px 10px 12px; - position: relative; -} - -.w-sdc-dashboard-card-avatar { - .uppercase; - border-radius: 50%; - display: inline-block; - position: absolute; - left: -6px; - text-align: center; - top: -6px; - - span { - - background-color: @main_color_p; - .border-radius(15px); - color: @color_c; - content: ''; - height: 30px; - text-align: center; - display: block; - border: solid 2px #ECEFF3; - padding: 3px 10px 2px 10px; - - &.VF { - .j_14_m; - &::before { - content: 'VF'; - } - } - - &.VFC { - .j_14_m; - &::before { - content: 'VFC'; - } - } - - &.CP { - .j_14_m; - &::before { - content: 'CP'; - } - } - - &.VL { - .j_14_m; - &::before { - content: 'VL'; - } - } - - &.SERVICE { - .c_14_m; - &::before { - content: 'S'; - } - } - - &.green { - .d_12; - &::before { - content: 'R'; - } - } - &.red { - .r_12; - &::before { - content: 'S'; - } - } - &.dblack { - .s_12; - &::before { - content: 'P'; - } - } - } -} - -.w-sdc-dashboard-card-info { - display: inline-block; - vertical-align: middle; - max-width: 165px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.w-sdc-dashboard-card-info-name-container{ - position: absolute; - bottom: 0; - left: 0; - margin: 0 0 2px 10px; -} -.w-sdc-dashboard-card-info-name { - .m_14_m; - display: inline-block; - vertical-align: middle; - max-width: 165px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.w-sdc-dashboard-card-info-lifecycleState { - .m_13_m; - display: inline-block; - vertical-align: middle; - max-width: 165px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.w-sdc-dashboard-card-info-user { - .n_13_r; - line-height: 18px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - width: 100%; -} - -.w-sdc-dashboard-card-menu-button { - display: inline-block; - padding: 12px 0 0 10px; - position: absolute; - right: 12px; - top: 8px; - border-left: solid 1px @color_k; - height: 42px; - - &:hover { - .w-sdc-dashboard-card-menu { - display: block; - } - } -} - -.w-sdc-dashboard-card-menu { - .bg_c; - border-radius: 0 0 4px 4px; - border-top: 3px solid @color_a; - box-shadow: 0 2px 2px 0px rgba(0, 0, 0, 0.2); - color: @color_s; - display: none; - min-height: 30px; - padding: 9px 0; - position: absolute; - right: -27px; - width: 208px; - z-index: 9; - max-height: 164px; - - &::before { - //TODO: Missing image for small blue triangle. - background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMDE0IDc5LjE1Njc5NywgMjAxNC8wOC8yMC0wOTo1MzowMiAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOkE1OTIzNDI1MENFQjExRTU4ODRERTI1MDM2REZCOUYzIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOkE1OTIzNDI2MENFQjExRTU4ODRERTI1MDM2REZCOUYzIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6QTU5MjM0MjMwQ0VCMTFFNTg4NERFMjUwMzZERkI5RjMiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6QTU5MjM0MjQwQ0VCMTFFNTg4NERFMjUwMzZERkI5RjMiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz4gBXTlAAAAOElEQVR42mK0rp7NgASMgZgFiE/CBJjQJPcA8U4gNkdXAJMUAGJ+ZEVMaJIwAFfEhEUSRRFAgAEAVtgJyiLAPWAAAAAASUVORK5CYII='); - content: ''; - display: block; - height: 21px; - position: absolute; - right: 24px; - top: -24px; - width: 184px; - background-repeat: no-repeat; - background-position: 175px 16px; - } -} - -.i-sdc-dashboard-card-menu-item { - .hand; - line-height: 24px; - padding: 0 10px; - &:hover { .a_7; } -} - -.w-sdc-dashboard-card-info-lifecycleState-icon{ - position:absolute; - bottom:18px; - right:10px; -} - -// Same for dashboard and catalog view. -.w-sdc-dashboard-card-schema-image { - position: absolute; - top: 41%; - - //TODO: Israel - remove this after getting the services sprite. - height: 45px; - width: 53px; - background-repeat: no-repeat; - - // Center the icon vertical and horizontal. - margin: auto; - left: 0; - right: 0; - top: -10px; - bottom: 0; -} - -/* dashboard card main icons */ -.w-sdc-dashboard-card-schema-image.service { .s-sdc-service } -.w-sdc-dashboard-card-schema-image.resource { .s-sdc-resource } - -/* dashboard card statuses icons */ -.w-sdc-dashboard-card-edit.NOT_CERTIFIED_CHECKIN { .sprite; .s-sdc-state.NOT_CERTIFIED_CHECKIN; } -.w-sdc-dashboard-card-edit.NOT_CERTIFIED_CHECKOUT { .sprite; .s-sdc-state.NOT_CERTIFIED_CHECKOUT; } -.w-sdc-dashboard-card-edit.CERTIFIED { .sprite; .s-sdc-state.CERTIFIED; } -.w-sdc-dashboard-card-edit.READY_FOR_CERTIFICATION { .sprite; .s-sdc-state.READY_FOR_CERTIFICATION; } -.w-sdc-dashboard-card-edit.CERTIFICATION_IN_PROGRESS { .sprite; .s-sdc-state.CERTIFICATION_IN_PROGRESS; } -.w-sdc-dashboard-card-edit.DISTRIBUTED { .sprite; .s-sdc-state.DISTRIBUTED; } - -.w-sdc-dashboard-card-avatar.green + .w-sdc-dashboard-card-edit.NOT_CERTIFIED_CHECKIN { .sprite; .s-sdc-state.NOT_CERTIFIED_CHECKIN.green; } -.w-sdc-dashboard-card-avatar.green + .w-sdc-dashboard-card-edit.NOT_CERTIFIED_CHECKOUT { .sprite; .s-sdc-state.NOT_CERTIFIED_CHECKOUT.green; } -.w-sdc-dashboard-card-avatar.green + .w-sdc-dashboard-card-edit.CERTIFIED { .sprite; .s-sdc-state.CERTIFIED.green; } -.w-sdc-dashboard-card-avatar.green + .w-sdc-dashboard-card-edit.READY_FOR_CERTIFICATION { .sprite; .s-sdc-state.READY_FOR_CERTIFICATION.green; } -.w-sdc-dashboard-card-avatar.green + .w-sdc-dashboard-card-edit.CERTIFICATION_IN_PROGRESS { .sprite; .s-sdc-state.CERTIFICATION_IN_PROGRESS.green; } -.w-sdc-dashboard-card-avatar.green + .w-sdc-dashboard-card-edit.DISTRIBUTED { .sprite; .s-sdc-state.DISTRIBUTED.green; } - -.w-sdc-dashboard-card-avatar.red + .w-sdc-dashboard-card-edit.NOT_CERTIFIED_CHECKIN { .sprite; .s-sdc-state.NOT_CERTIFIED_CHECKIN.red; } -.w-sdc-dashboard-card-avatar.red + .w-sdc-dashboard-card-edit.NOT_CERTIFIED_CHECKOUT { .sprite; .s-sdc-state.NOT_CERTIFIED_CHECKOUT.red; } -.w-sdc-dashboard-card-avatar.red + .w-sdc-dashboard-card-edit.CERTIFIED { .sprite; .s-sdc-state.CERTIFIED.red; } -.w-sdc-dashboard-card-avatar.red + .w-sdc-dashboard-card-edit.READY_FOR_CERTIFICATION { .sprite; .s-sdc-state.READY_FOR_CERTIFICATION.red; } -.w-sdc-dashboard-card-avatar.red + .w-sdc-dashboard-card-edit.CERTIFICATION_IN_PROGRESS { .sprite; .s-sdc-state.CERTIFICATION_IN_PROGRESS.red; } -.w-sdc-dashboard-card-avatar.red + .w-sdc-dashboard-card-edit.DISTRIBUTED { .sprite; .s-sdc-state.DISTRIBUTED.red; } diff --git a/catalog-ui/src/app/view-models/dcae-app/dcae-app-view-model.ts b/catalog-ui/src/app/view-models/dcae-app/dcae-app-view-model.ts index 19bc548e74..e6ac97085a 100644 --- a/catalog-ui/src/app/view-models/dcae-app/dcae-app-view-model.ts +++ b/catalog-ui/src/app/view-models/dcae-app/dcae-app-view-model.ts @@ -22,7 +22,7 @@ import * as _ from "lodash"; import {MenuItemGroup, MenuItem} from "app/utils"; import {BreadcrumbsPath, BreadcrumbsMenu} from "../onboard-vendor/onboard-vendor-view-model"; -import {CacheService} from "app/services"; +import {CacheService} from "app/services-ng2"; import {IUserProperties} from "app/models"; export class TestData { diff --git a/catalog-ui/src/app/view-models/dcae-app/dcae-app-view.html b/catalog-ui/src/app/view-models/dcae-app/dcae-app-view.html index 9dbe289ba2..a1e084108a 100644 --- a/catalog-ui/src/app/view-models/dcae-app/dcae-app-view.html +++ b/catalog-ui/src/app/view-models/dcae-app/dcae-app-view.html @@ -13,7 +13,6 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> -
    diff --git a/catalog-ui/src/app/view-models/dcae-app/dcae-app.less b/catalog-ui/src/app/view-models/dcae-app/dcae-app.less index 71a3101412..1e091e957d 100644 --- a/catalog-ui/src/app/view-models/dcae-app/dcae-app.less +++ b/catalog-ui/src/app/view-models/dcae-app/dcae-app.less @@ -76,22 +76,6 @@ } } - &.READY_FOR_CERTIFICATION { - .i-sdc-categories-list-item-icon { - background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -2985px; - width: 14px; - height: 16px; - } - } - - &.CERTIFICATION_IN_PROGRESS { - .i-sdc-categories-list-item-icon { - background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -2934px; - width: 14px; - height: 16px; - } - } - &.DISTRIBUTED, &.TBD { .i-sdc-categories-list-item-icon { diff --git a/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form-view-model.ts b/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form-view-model.ts deleted file mode 100644 index 45ebb12351..0000000000 --- a/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form-view-model.ts +++ /dev/null @@ -1,379 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import * as _ from "lodash"; -import {ArtifactModel, Resource, Component} from "app/models"; -import {ArtifactsUtils, FormState, ValidationUtils, ArtifactType} from "app/utils"; -import {CacheService} from "app/services"; - -export interface IEditArtifactModel { - artifactResource:ArtifactModel; - artifactTypes:Array; - artifactFile:any; -} - -export interface IArtifactResourceFormViewModelScope extends ng.IScope { - forms:any; - $$childTail:any; - isNew:boolean; - isLoading:boolean; - validationPattern:RegExp; - urlValidationPattern:RegExp; - labelValidationPattern:RegExp; - integerValidationPattern:RegExp; - commentValidationPattern:RegExp; - artifactType:string; - editArtifactResourceModel:IEditArtifactModel; - defaultHeatTimeout:number; - validExtensions:any; - originalArtifactName:string; - editForm:ng.IFormController; - footerButtons:Array; - modalInstanceArtifact:ng.ui.bootstrap.IModalServiceInstance; - - fileExtensions():string; - save(doNotCloseModal?:boolean):void; - saveAndAnother():void; - close():void; - getOptions():Array; - isDeploymentHeat():boolean; - onFileChange():void; - setDefaultTimeout():void; - openEditEnvParametersModal(artifact:ArtifactModel):void; - getFormTitle():string; - fileUploadRequired():string; - isArtifactOwner():boolean; -} - -export class ArtifactResourceFormViewModel { - - static '$inject' = [ - '$scope', - '$uibModalInstance', - 'artifact', - 'Sdc.Services.CacheService', - 'ValidationPattern', - 'UrlValidationPattern', - 'LabelValidationPattern', - 'IntegerValidationPattern', - 'CommentValidationPattern', - 'ValidationUtils', - '$base64', - '$state', - 'ArtifactsUtils', - '$uibModal', - 'component' - ]; - - private formState:FormState; - private entityId:string; - - constructor(private $scope:IArtifactResourceFormViewModelScope, - private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance, - private artifact:ArtifactModel, - private cacheService:CacheService, - private ValidationPattern:RegExp, - private UrlValidationPattern:RegExp, - private LabelValidationPattern:RegExp, - private IntegerValidationPattern:RegExp, - private CommentValidationPattern:RegExp, - private ValidationUtils:ValidationUtils, - private $base64:any, - private $state:any, - private artifactsUtils:ArtifactsUtils, - private $uibModal:ng.ui.bootstrap.IModalService, - private component:Component) { - - - this.entityId = this.component.uniqueId; - this.formState = angular.isDefined(artifact.artifactLabel) ? FormState.UPDATE : FormState.CREATE; - this.initScope(); - } - - private initEntity = ():void => { - this.$scope.editArtifactResourceModel.artifactResource = this.artifact; - this.$scope.originalArtifactName = this.artifact.artifactName; - }; - - - private initFooterButtons = ():void => { - - this.$scope.footerButtons = [ - {'name': 'Done', 'css': 'blue', 'callback': this.$scope.save} - ]; - if (this.$scope.isNew) { - this.$scope.footerButtons.push({ - 'name': 'Add Another', - 'css': 'grey', - 'disabled': !this.$scope.isNew && 'deployment' === this.$scope.artifactType, - 'callback': this.$scope.saveAndAnother - }); - } - }; - - private filterDeploymentArtifactTypeByResourceType = (resourceType:string):any => { - let result = {}; - _.each(this.$scope.validExtensions, function (typeSettings:any, typeName:string) { - if (!typeSettings.validForResourceTypes || typeSettings.validForResourceTypes.indexOf(resourceType) > -1) { - result[typeName] = typeSettings; - } - }); - - return result; - }; - - private initArtifactTypes = ():void => { - - let artifactTypes:any = this.cacheService.get('UIConfiguration'); - - if ('deployment' === this.$scope.artifactType) { - - - if ('HEAT_ENV' == this.artifact.artifactType || this.component.selectedInstance) { - this.$scope.validExtensions = artifactTypes.artifacts.deployment.resourceInstanceDeploymentArtifacts; - } else if (this.component.isResource()) { - this.$scope.validExtensions = artifactTypes.artifacts.deployment.resourceDeploymentArtifacts; - this.$scope.validExtensions = this.filterDeploymentArtifactTypeByResourceType((this.component).resourceType); - } else { - this.$scope.validExtensions = artifactTypes.artifacts.deployment.serviceDeploymentArtifacts; - } - - if (this.$scope.validExtensions) { - this.$scope.editArtifactResourceModel.artifactTypes = Object.keys(this.$scope.validExtensions); - } - this.$scope.defaultHeatTimeout = artifactTypes.defaultHeatTimeout; - if (this.$scope.isNew) { - let isHeat = 'HEAT_ENV' == this.artifact.artifactType; - _.remove(this.$scope.editArtifactResourceModel.artifactTypes, (item:string)=> { - return 'HEAT' == item.substring(0, 4) || (!isHeat && item == "VF_MODULES_METADATA") || - _.has(ArtifactType.THIRD_PARTY_RESERVED_TYPES, item); - }); - } - - } - if (this.$scope.artifactType === 'informational') { - this.$scope.editArtifactResourceModel.artifactTypes = artifactTypes.artifacts.other.map((element:any)=> { - return element.name; - }); - _.remove(this.$scope.editArtifactResourceModel.artifactTypes, (item:string)=> { - return _.has(ArtifactType.THIRD_PARTY_RESERVED_TYPES, item) || - _.has(ArtifactType.TOSCA, item); - }) - } - - if (this.component.isResource() && (this.component).isCsarComponent()) { - _.remove(this.$scope.editArtifactResourceModel.artifactTypes, (item:string) => { - return this.artifactsUtils.isLicenseType(item); - }) - } - - }; - - private initEditArtifactResourceModel = ():void => { - this.$scope.editArtifactResourceModel = { - artifactResource: null, - artifactTypes: null, - artifactFile: {} - }; - - this.initEntity(); - }; - - private initScope = ():void => { - - this.$scope.validationPattern = this.ValidationPattern; - this.$scope.urlValidationPattern = this.UrlValidationPattern; - this.$scope.labelValidationPattern = this.LabelValidationPattern; - this.$scope.integerValidationPattern = this.IntegerValidationPattern; - this.$scope.commentValidationPattern = this.CommentValidationPattern; - this.$scope.isLoading = false; - this.$scope.isNew = (this.formState === FormState.CREATE); - this.$scope.artifactType = this.artifactsUtils.getArtifactTypeByState(this.$state.current.name); - this.$scope.modalInstanceArtifact = this.$uibModalInstance; - - this.initEditArtifactResourceModel(); - this.initArtifactTypes(); - - // In case of edit, show the file name in browse. - if (this.artifact.artifactName !== "" && 'HEAT_ENV' !== this.artifact.artifactType) { - this.$scope.editArtifactResourceModel.artifactFile = {}; - this.$scope.editArtifactResourceModel.artifactFile.filename = this.artifact.artifactName; - } - - //scope methods - this.$scope.isDeploymentHeat = ():boolean => { - return !this.$scope.isNew && this.$scope.artifactType === 'deployment' - && this.$scope.editArtifactResourceModel.artifactResource.isHEAT(); - - }; - this.$scope.onFileChange = ():void => { - if (this.$scope.editArtifactResourceModel.artifactFile && this.$scope.editArtifactResourceModel.artifactFile.filename) { - this.$scope.editArtifactResourceModel.artifactResource.artifactName = this.$scope.editArtifactResourceModel.artifactFile.filename; - } else { - this.$scope.editArtifactResourceModel.artifactResource.artifactName = this.$scope.originalArtifactName; - } - }; - this.$scope.setDefaultTimeout = ():void => { - if (this.$scope.isDeploymentHeat() && !this.$scope.editArtifactResourceModel.artifactResource.timeout) { - this.$scope.editArtifactResourceModel.artifactResource.timeout = this.$scope.defaultHeatTimeout; - } - - if (this.$scope.editArtifactResourceModel.artifactFile && this.$scope.editArtifactResourceModel.artifactFile.filename) { - this.$scope.editArtifactResourceModel.artifactFile = {}; - this.$scope.forms.editForm.myArtifactFile.$setValidity('required', false); - } - }; - - this.$scope.fileExtensions = ():string => { - let type:string = this.$scope.editArtifactResourceModel.artifactResource.artifactType; - return type && this.$scope.validExtensions && this.$scope.validExtensions[type].acceptedTypes ? - this.$scope.validExtensions[type].acceptedTypes.join(',') : ""; - }; - - this.$scope.save = (doNotCloseModal?:boolean):void => { - this.$scope.isLoading = true; - this.$scope.editArtifactResourceModel.artifactResource.description = this.ValidationUtils.stripAndSanitize(this.$scope.editArtifactResourceModel.artifactResource.description); - - if (!this.$scope.isDeploymentHeat()) { - this.$scope.editArtifactResourceModel.artifactResource.timeout = null; - } - - if (this.$scope.editArtifactResourceModel.artifactFile) { - this.$scope.editArtifactResourceModel.artifactResource.payloadData = this.$scope.editArtifactResourceModel.artifactFile.base64; - this.$scope.editArtifactResourceModel.artifactResource.artifactName = this.$scope.editArtifactResourceModel.artifactFile.filename; - } - - let onFaild = (response):void => { - this.$scope.isLoading = false; - console.info('onFaild', response); - }; - - let onSuccess = (artifactResource:ArtifactModel):void => { - this.$scope.isLoading = false; - this.$scope.originalArtifactName = ""; - - if (this.$scope.isDeploymentHeat()) { - if (artifactResource.heatParameters) { - this.$scope.openEditEnvParametersModal(artifactResource); - } - } - - if (!doNotCloseModal) { - this.$uibModalInstance.close(); - } else { - this.$scope.editArtifactResourceModel.artifactFile = null; - angular.element("input[type='file']").val(null); // for support chrome when upload the same file - this.artifactsUtils.addAnotherAfterSave(this.$scope); - } - - }; - - if ('HEAT_ENV' == this.artifact.artifactType) { - if (this.component.selectedInstance) { - this.component.uploadInstanceEnvFile(this.$scope.editArtifactResourceModel.artifactResource).then(onSuccess, onFaild); - } else { - this.component.addOrUpdateArtifact(this.$scope.editArtifactResourceModel.artifactResource).then(onSuccess, onFaild); - - } - } else if (this.$scope.isArtifactOwner()) { - this.component.addOrUpdateInstanceArtifact(this.$scope.editArtifactResourceModel.artifactResource).then(onSuccess, onFaild); - } else { - this.component.addOrUpdateArtifact(this.$scope.editArtifactResourceModel.artifactResource).then(onSuccess, onFaild); - } - }; - - this.$scope.isArtifactOwner = ():boolean=> { - return this.component.isService() && !!this.component.selectedInstance; - }; - - this.$scope.saveAndAnother = ():void => { - this.$scope.save(true); - }; - - this.$scope.close = ():void => { - this.$uibModalInstance.close(); - }; - - this.$scope.fileUploadRequired = ():string => { - if (this.$scope.editArtifactResourceModel.artifactFile.filename) { - // This is edit mode - return 'false'; - } else { - return 'true'; - } - }; - - this.$scope.getFormTitle = ():string => { - if ('HEAT_ENV' == this.artifact.artifactType) { - return 'Update HEAT ENV'; - } - if (this.$scope.isDeploymentHeat()) { - if (!this.$scope.editArtifactResourceModel.artifactResource.artifactChecksum) { - return 'Add HEAT Template'; - } - return 'Update HEAT Template'; - } - if (this.$scope.isNew) { - return 'Add Artifact'; - } - return 'Update Artifact'; - }; - - this.$scope.openEditEnvParametersModal = (artifactResource:ArtifactModel):void => { - - let modalOptions:ng.ui.bootstrap.IModalSettings = { - templateUrl: '../env-parameters-form/env-parameters-form.html', - controller: 'Sdc.ViewModels.EnvParametersFormViewModel', - size: 'sdc-md', - backdrop: 'static', - resolve: { - artifact: ():ArtifactModel => { - return artifactResource; - }, - component: ():Component => { - return this.component; - } - } - }; - - let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions); - modalInstance - .result - .then(():void => { - }); - }; - - this.$scope.forms = {}; - - this.initFooterButtons(); - - - this.$scope.$watch("forms.editForm.$invalid", (newVal, oldVal) => { - if(this.$scope.forms.editForm) { - this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid; - if (this.$scope.isNew) { - this.$scope.footerButtons[1].disabled = this.$scope.forms.editForm.$invalid; - } - } - }); - - } -} diff --git a/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form-view.html b/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form-view.html deleted file mode 100644 index 61ebcc8a28..0000000000 --- a/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form-view.html +++ /dev/null @@ -1,185 +0,0 @@ - - - - - - -
    -
    - - -
    - - - -
    - - - - -
    -
    - - -
    - -
    - -
    - - - -
    - - - -
    - -
    - -
    - - - -
    - -
    - -
    - -
    - - - -
    - - - -
    - -
    - -
    - -
    - -
    - - - -
    - - - -
    - -
    - -
    - -
    - -
    - - - -
    - - - -
    - -
    - UUID -
    - Version -
    -
    - -
    - -
    - - - -
    -
    -
    - diff --git a/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form.less b/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form.less deleted file mode 100644 index 1f77958c88..0000000000 --- a/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form.less +++ /dev/null @@ -1,44 +0,0 @@ -.sdc-edit-artifact-form-container { - - .w-sdc-form-note { - .h_9; - display: block; - position: relative; - top: 13px; - } - - .i-sdc-form-textarea{ - min-height: 95px; - } - - .i-sdc-form-url { - padding-bottom: 0px; - } - - &.mandatory-artifact { - .w-sdc-form-column { - width: 100%; - padding: 0; - min-height: initial; - } - } - .w-sdc-form .i-sdc-form-item.upload input[type="file"] { - display: none - } - - .artifact-info { - text-align: left; - color: rgb(140, 140, 140); - font-size: 13px; - margin-top: -10px; - margin-bottom: 5px; - width: 100%; - min-height: initial; - - span { - color: #666666; - padding-left: 4px; - } - } - -} diff --git a/catalog-ui/src/app/view-models/forms/attribute-form/attribute-form-view.html b/catalog-ui/src/app/view-models/forms/attribute-form/attribute-form-view.html deleted file mode 100644 index 902d564935..0000000000 --- a/catalog-ui/src/app/view-models/forms/attribute-form/attribute-form-view.html +++ /dev/null @@ -1,168 +0,0 @@ - - - - -
    -
    - -
    - -
    - - -
    - - -
    - - - - -
    -
    - - -
    - - -
    - - - -
    -
    - - -
    - -
    - -
    - - -
    - -
    -
    - - -
    - - - -
    - -
    -
    - - -
    - - - -
    - - - - -
    -
    - - -
    - - -
    -
    - -
    - -
    -
    - -
    diff --git a/catalog-ui/src/app/view-models/forms/attribute-form/attribute-from-view-model.ts b/catalog-ui/src/app/view-models/forms/attribute-form/attribute-from-view-model.ts deleted file mode 100644 index 0e4a851aa6..0000000000 --- a/catalog-ui/src/app/view-models/forms/attribute-form/attribute-from-view-model.ts +++ /dev/null @@ -1,262 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import * as _ from "lodash"; -import {AttributeModel, Component} from "app/models"; -import {IMapRegex, ValidationUtils, FormState, PROPERTY_TYPES} from "app/utils"; - -export interface IEditAttributeModel { - attribute:AttributeModel; - types:Array; - simpleTypes:Array; -} - -export class attributeValue {//in order to solve DE226783, we update the value on another obj - value:string; -} - -interface IAttributeFormViewModelScope extends ng.IScope { - $$childTail:any; - forms:any; - editForm:ng.IFormController; - footerButtons:Array; - isService:boolean; - editAttributeModel:IEditAttributeModel; - modalInstanceAttribute:ng.ui.bootstrap.IModalServiceInstance; - isNew:boolean; - listRegex:IMapRegex; - mapRegex:IMapRegex; - propertyNameValidationPattern:RegExp; - commentValidationPattern:RegExp; - isLoading:boolean; - validationPattern:RegExp; - attributeValue:attributeValue; - - save():void; - close():void; - onTypeChange():void; - onValueChange():void; - isAttributeValueOwner():boolean; - validateIntRange(value:string):boolean; - validateUniqueKeys(viewValue:string):boolean; - getValidationTranslate():string; - showSchema():boolean; - isSchemaEditable():boolean; - validateName():void; -} - -export class AttributeFormViewModel { - - static '$inject' = [ - '$scope', - '$uibModalInstance', - 'attribute', - 'ValidationUtils', - 'CommentValidationPattern', - 'PropertyNameValidationPattern', - 'component' - ]; - - private formState:FormState; - - - constructor(private $scope:IAttributeFormViewModelScope, - private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance, - private attribute:AttributeModel, - private ValidationUtils:ValidationUtils, - private CommentValidationPattern:RegExp, - private PropertyNameValidationPattern:RegExp, - private component:Component) { - this.formState = angular.isDefined(attribute.name) ? FormState.UPDATE : FormState.CREATE; - this.initScope(); - } - - private initResource = ():void => { - this.$scope.editAttributeModel.attribute = new AttributeModel(this.attribute); - if (this.$scope.editAttributeModel.types.indexOf(this.attribute.type) === -1) {//attribute defaulte type is string too? - this.attribute.type = "string"; - } - }; - - private initEditAttributeModel = ():void => { - this.$scope.editAttributeModel = { - attribute: null, - types: ['integer', 'string', 'float', 'boolean', 'list', 'map'], - simpleTypes: ['integer', 'string', 'float', 'boolean'] - }; - - this.initResource(); - }; - - private initScope = ():void => { - - //scope attributes - this.$scope.forms = {}; - this.$scope.propertyNameValidationPattern = this.PropertyNameValidationPattern; - this.$scope.commentValidationPattern = this.CommentValidationPattern; - - this.$scope.modalInstanceAttribute = this.$uibModalInstance; - this.$scope.listRegex = this.ValidationUtils.getPropertyListPatterns(); - this.$scope.mapRegex = this.ValidationUtils.getPropertyMapPatterns(); - - this.$scope.isNew = (this.formState === FormState.CREATE); - this.$scope.isLoading = false; - this.$scope.attributeValue = new attributeValue(); - - this.initEditAttributeModel(); - this.setValidationPattern(); - - //scope methods - this.$scope.save = ():void => { - if (!this.$scope.forms.editForm.$invalid) { - let attribute:AttributeModel = this.$scope.editAttributeModel.attribute; - this.$scope.editAttributeModel.attribute.description = this.ValidationUtils.stripAndSanitize(this.$scope.editAttributeModel.attribute.description); - ////if read only - just closes the modal - if (this.$scope.editAttributeModel.attribute.readonly && !this.$scope.isAttributeValueOwner()) { - this.$uibModalInstance.close(); - return; - } - this.$scope.isLoading = true; - let onAttributeFaild = (response):void => { - console.info('onFaild', response); - this.$scope.isLoading = false; - }; - - let onAttributeSuccess = (attributeFromBE:AttributeModel):void => { - console.info('onAttributeResourceSuccess : ', attributeFromBE); - this.$scope.isLoading = false; - this.$uibModalInstance.close(); - }; - - //in case we have uniqueId we call update method - if (this.$scope.isAttributeValueOwner()) { - attribute.value = this.$scope.attributeValue.value; - this.component.updateInstanceAttribute(attribute).then(onAttributeSuccess, onAttributeFaild); - } else { - attribute.defaultValue = this.$scope.attributeValue.value; - this.component.addOrUpdateAttribute(attribute).then(onAttributeSuccess, onAttributeFaild); - } - } - }; - - this.$scope.close = ():void => { - this.$uibModalInstance.close(); - }; - - this.$scope.validateName = ():void => { - let existsAttr:AttributeModel = _.find(this.component.attributes, (attribute:AttributeModel) => { - return attribute.name === this.$scope.editAttributeModel.attribute.name; - }); - if (existsAttr) { - this.$scope.forms.editForm["attributeName"].$setValidity('nameExist', false); - } else { - this.$scope.forms.editForm["attributeName"].$setValidity('nameExist', true); - } - - }; - - this.$scope.onTypeChange = ():void => { - this.$scope.editAttributeModel.attribute.value = ''; - this.$scope.editAttributeModel.attribute.defaultValue = ''; - this.setValidationPattern(); - }; - - this.$scope.isAttributeValueOwner = ():boolean=> { - return this.component.isService() || !!this.component.selectedInstance; - }; - - this.$scope.onValueChange = ():void => { - if (!this.$scope.editAttributeModel.attribute.value) { - if (this.$scope.isAttributeValueOwner()) { - this.$scope.editAttributeModel.attribute.value = this.$scope.editAttributeModel.attribute.defaultValue; - } - } - }; - - - this.$scope.validateUniqueKeys = (viewValue:string):boolean => { - if (this.$scope.editAttributeModel.attribute.type === 'map') { - return this.ValidationUtils.validateUniqueKeys(viewValue); - } - else { - return true; //always valid if not a map - } - }; - - this.$scope.validateIntRange = (value:string):boolean => { - return !value || this.ValidationUtils.validateIntRange(value); - }; - - this.$scope.isSchemaEditable = ():boolean => { - let schemaType = this.$scope.editAttributeModel.attribute.schema.property.type; - return this.$scope.editAttributeModel.simpleTypes.indexOf(schemaType) > -1 || !schemaType; - }; - - this.$scope.showSchema = ():boolean => { - return ['list', 'map'].indexOf(this.$scope.editAttributeModel.attribute.type) > -1; - }; - - this.$scope.getValidationTranslate = ():string => { - let result = "ATTRIBUTE_EDIT_PATTERN"; - if (this.$scope.showSchema()) { - - result = "ATTRIBUTE_EDIT_" + this.$scope.editAttributeModel.attribute.type.toUpperCase(); - - if (this.$scope.editAttributeModel.attribute.schema.property.type === PROPERTY_TYPES.STRING) { - result += "_STRING"; - } else if (this.$scope.editAttributeModel.attribute.schema.property.type === PROPERTY_TYPES.BOOLEAN) { - result += "_BOOLEAN"; - } else { - result += "_GENERIC"; - } - } - - return result; - }; - - // Add the done button at the footer. - this.$scope.footerButtons = [ - {'name': 'Done', 'css': 'blue', 'callback': this.$scope.save}, - {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close} - ]; - - this.$scope.$watchCollection("forms.editForm.$invalid", (newVal, oldVal) => { - this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid; - }); - - this.$scope.attributeValue.value = this.$scope.isAttributeValueOwner() ? this.$scope.editAttributeModel.attribute.value : this.$scope.editAttributeModel.attribute.defaultValue; - }; - - - private setValidationPattern = ():void => { - - if (this.$scope.editAttributeModel.attribute.type === 'list') { - this.$scope.validationPattern = this.$scope.listRegex[this.$scope.editAttributeModel.attribute.schema.property.type]; - } - else if (this.$scope.editAttributeModel.attribute.type === 'map') { - this.$scope.validationPattern = this.$scope.mapRegex[this.$scope.editAttributeModel.attribute.schema.property.type]; - } - else { - this.$scope.validationPattern = this.ValidationUtils.getValidationPattern(this.$scope.editAttributeModel.attribute.type); - } - - }; -} diff --git a/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.html b/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.html deleted file mode 100644 index b3d64818ba..0000000000 --- a/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.html +++ /dev/null @@ -1,108 +0,0 @@ - - - -
    - -
    -
    -
    -
    - - {{header.title}} -
    -
    -
    - - -
    -
    - {{parameter.name}} - -
    - -
    - {{parameter.defaultValue}} -
    - - - - - -
    - -
    - * -
    - - -
    -
    -
    -
    -
    -
    -
    -
    - - - -
    -
    - -
    - -
    -
    - -
    -
    -
    -
    -
    -
    - diff --git a/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.less b/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.less deleted file mode 100644 index d89ab37030..0000000000 --- a/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.less +++ /dev/null @@ -1,177 +0,0 @@ -.sdc-env-form-container{ - .w-sdc-modal-body{ - padding: 20px 10px 2px 10px; - } - .w-sdc-modal-body-content{ - .b_6; - display: block; - } - - .env-file-generation-label{ - .p_9; - .bold; - margin-bottom: 20px; - } -} - -.w-sdc-env-form-container { - height: 650px; - - .w-sdc-env-search { - padding: 10px 20px 20px 0; - white-space: nowrap; - position: relative; - width: 60%; - height: 64px; - - .env-search-icon { - top: 9px; - right: 11px; - } - - .magnification-white { - .sprite-new; - .search-white-icon; - .hand; - } - - .search-icon-container { - width: 35px; - height: 30px; - background-color: @main_color_a; - white-space: nowrap; - float: right; - position: relative; - bottom: 31px; - right: 1px; - border-radius: 0px 4px 4px 0px; - .hand - } - - .w-sdc-env-search-input { - border: 1px solid @color_e; - .border-radius(4px); - height: 32px; - margin: 0; - padding: 0px 28px 3px 10px; - vertical-align: 4px; - width: 100%; - outline: none; - font-style: italic; - } - } - - .table-container-flex { - height: 570px; - - .table { - height: 100%; - .flex-item:nth-child(1) { - flex-grow: 20; - .show-desc{ - float: right; - top: 10px; - position: relative; - } - } - - .flex-item:nth-child(2) { - flex-grow: 10; - } - - .flex-item:nth-child(3) { - flex-grow: 10; - } - .scrollbar-container{ - max-height: 527px; - } - .left-column-container{ - .required-symbol { - .m_14_m; - color: #f33; - display: none; - position: relative; - left: -4px; - top: 3px; - } - - .i-sdc-form-item{ - border-right: none; - margin: 0px; - - .input-parameter{ - border: none; - height: 30px; - width: 254px; - float: right; - input{ - .m_13_m; - width: 100%; - display: inline-flex; - padding-right: 33px; - } - .action-button{ - border-left: solid 1px @main_color_o; - position: relative; - height: 20px; - width: 25px; - top: -25px; - left: 228px; - padding-left: 6px; - background-color: @main_color_p; - div:not(.disable){ - .hand; - } - } - } - - &.required{ - .required-symbol { - display: inline-flex; - } - .input-parameter { - width: 250px; - } - .action-button{ - left: 224px; - } - } - } - - - - } - } - - .text{ - overflow: hidden; - text-overflow: ellipsis; - display: inline-block; - white-space: nowrap; - } - } - - - .parameter-description{ - background-color: @func_color_r; - border-left: 4px solid @main_color_a; - padding: 10px 30px; - } -} - -.header-info{ - float: right; -} - -.parameter-description-popover{ - z-index: 1100; - min-width: 210px; - .arrow{ - left: 20px !important; - border-width: 7px; - bottom: -8px !important; - } - .popover-content{ - .f-type._13_m;; - } -} diff --git a/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.ts b/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.ts deleted file mode 100644 index a30fd15c63..0000000000 --- a/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parameters-form.ts +++ /dev/null @@ -1,184 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {ValidationUtils} from "app/utils"; -import {ArtifactModel, HeatParameterModel, Component} from "app/models"; - -export interface IEnvParametersFormViewModelScope extends ng.IScope { - isLoading:boolean; - type:string; - heatParameters:Array; - forms:any; - artifactResource:ArtifactModel; - buttons:Array; - envParametersModal:ng.ui.bootstrap.IModalServiceInstance; - tableHeadersList:Array; - selectedParameter:HeatParameterModel; - templatePopover:string; - - getValidationPattern(type:string):RegExp; - isInstance():boolean; - validateJson(json:string):boolean; - onValueChanged(parameter: HeatParameterModel):void; - close():void; - save():void; - openDescPopover(selectedParam:HeatParameterModel):void; - closeDescriptionPopover():void; -} - -export class EnvParametersFormViewModel { - - static '$inject' = [ - '$scope', - '$templateCache', - '$state', - '$uibModalInstance', - 'artifact', - 'ValidationUtils', - 'component' - ]; - - constructor(private $scope:IEnvParametersFormViewModelScope, - private $templateCache:ng.ITemplateCacheService, - private $state:any, - private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance, - private artifact:ArtifactModel, - private ValidationUtils:ValidationUtils, - private component:Component) { - - - this.initScope(); - } - - private updateInstanceHeat = ():void => { - let success = (responseArtifact:ArtifactModel):void => { - this.$scope.isLoading = false; - this.$uibModalInstance.close(); - }; - - let error = ():void => { - this.$scope.isLoading = false; - console.info('Failed to load save artifact'); - }; - - this.component.addOrUpdateInstanceArtifact(this.$scope.artifactResource).then(success, error); - }; - - private initScope = ():void => { - this.$scope.forms = {}; - this.$scope.envParametersModal = this.$uibModalInstance; - this.$scope.artifactResource = this.artifact; - this.$scope.heatParameters = angular.copy(this.artifact.heatParameters); - //if param does not have a value - display the default - this.$scope.heatParameters.forEach((heatParam) => { - heatParam.currentValue = heatParam.currentValue || heatParam.defaultValue; - }); - this.$scope.tableHeadersList = [ - {title: "Parameter", property: "name"}, - {title: "Default Value", property: "defaultValue", info: "DEFAULT_VALUE_INFO"}, - {title: "Current Value", property: "currentValue", info: "CURRENT_VALUE_INFO"} - ]; - - this.$templateCache.put("env-parametr-description-popover.html", require('app/view-models/forms/env-parameters-form/env-parametr-description-popover.html')); - this.$scope.templatePopover = "env-parametr-description-popover.html"; - - this.$scope.getValidationPattern = (validationType:string, parameterType?:string):RegExp => { - return this.ValidationUtils.getValidationPattern(validationType, parameterType); - }; - - this.$scope.validateJson = (json:string):boolean => { - if (!json) { - return true; - } - return this.ValidationUtils.validateJson(json); - }; - - this.$scope.isInstance = ():boolean => { - return !!this.component.selectedInstance; - }; - - this.$scope.save = ():void => { - this.$scope.buttons[0].disabled = true;//prevent double click (DE246266) - this.$scope.isLoading = true; - this.artifact.heatParameters = angular.copy(this.$scope.heatParameters); - this.artifact.heatParameters.forEach((parameter:any):void => { - if ("" === parameter.currentValue) { - //[Bug 154465] - Update and erase current value field in Env parameters form return empty String ("") instead of null. - parameter.currentValue = null; - } else if (parameter.defaultValue && parameter.defaultValue == parameter.currentValue) { - parameter.currentValue = undefined; - } - }); - - if (this.$scope.isInstance()) { - this.updateInstanceHeat(); - return; - } - - let success = (responseArtifact:ArtifactModel):void => { - this.$scope.isLoading = false; - this.$uibModalInstance.close(); - - }; - - let error = ():void => { - this.$scope.isLoading = false; - console.info('Failed to load save artifact'); - }; - - this.component.addOrUpdateArtifact(this.$scope.artifactResource).then(success, error); - }; - - this.$scope.onValueChanged = (parameter: HeatParameterModel):void => { - parameter.filterTerm = parameter.name + ' ' + parameter.currentValue + ' ' + parameter.defaultValue + ' ' +parameter.description - if('json'==parameter.type){ - this.$scope.forms.editForm[parameter.name].$setValidity('pattern', this.$scope.validateJson(parameter.currentValue)); - } - } - - this.$scope.close = ():void => { - //this.artifact.heatParameters.forEach((parameter:any):void => { - // if (!parameter.currentValue && parameter.defaultValue) { - // parameter.currentValue = parameter.defaultValue; - // } - //}); - this.$uibModalInstance.dismiss(); - }; - - this.$scope.openDescPopover = (selectedParam:HeatParameterModel):void => { - this.$scope.selectedParameter = selectedParam; - }; - - this.$scope.closeDescriptionPopover = ():void => { - this.$scope.selectedParameter = null; - }; - - this.$scope.buttons = [ - {'name': 'Save', 'css': 'blue', 'callback': this.$scope.save}, - {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close} - ]; - - this.$scope.$watch("forms.editForm.$invalid", (newVal, oldVal) => { - this.$scope.buttons[0].disabled = this.$scope.forms.editForm.$invalid; - }); - - }; -} diff --git a/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parametr-description-popover.html b/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parametr-description-popover.html deleted file mode 100644 index 6db354a072..0000000000 --- a/catalog-ui/src/app/view-models/forms/env-parameters-form/env-parametr-description-popover.html +++ /dev/null @@ -1,20 +0,0 @@ - - -
    - - {{selectedParameter.description}} -
    diff --git a/catalog-ui/src/app/view-models/forms/input-form/input-form-view-modal.ts b/catalog-ui/src/app/view-models/forms/input-form/input-form-view-modal.ts deleted file mode 100644 index 56542b9694..0000000000 --- a/catalog-ui/src/app/view-models/forms/input-form/input-form-view-modal.ts +++ /dev/null @@ -1,146 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {FormState, PROPERTY_TYPES, ValidationUtils, PROPERTY_VALUE_CONSTRAINTS} from "app/utils"; -import {InputModel} from "app/models"; - -export interface IInputEditModel { - editInput:InputModel; -} - -export interface IInputFormViewModelScope extends ng.IScope { - forms:any; - editForm:ng.IFormController; - footerButtons:Array; - isService:boolean; - modalInstanceInput:ng.ui.bootstrap.IModalServiceInstance; - isLoading:boolean; - inputEditModel:IInputEditModel; - myValue:any; - maxLength:number; - - save():void; - close():void; - validateIntRange(value:string):boolean; - validateJson(json:string):boolean; - getValidationPattern(type:string):RegExp; - showSchema():boolean; -} - -export class InputFormViewModel { - - static '$inject' = [ - '$scope', - '$uibModalInstance', - 'ValidationUtils', - 'input' - ]; - - private formState:FormState; - - - constructor(private $scope:IInputFormViewModelScope, - private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance, - private ValidationUtils:ValidationUtils, - private input:InputModel) { - this.initScope(); - this.initMyValue(); - } - - private initMyValue = ():void => { - switch (this.$scope.inputEditModel.editInput.type) { - case PROPERTY_TYPES.MAP: - this.$scope.myValue = this.$scope.inputEditModel.editInput.defaultValue ? JSON.parse(this.$scope.inputEditModel.editInput.defaultValue) : {'': null}; - break; - case PROPERTY_TYPES.LIST: - this.$scope.myValue = this.$scope.inputEditModel.editInput.defaultValue ? JSON.parse(this.$scope.inputEditModel.editInput.defaultValue) : []; - break; - } - }; - - private initDefaultValueMaxLength = ():void => { - switch (this.$scope.inputEditModel.editInput.type) { - case PROPERTY_TYPES.MAP: - case PROPERTY_TYPES.LIST: - this.$scope.maxLength = this.$scope.inputEditModel.editInput.schema.property.type == PROPERTY_TYPES.JSON ? - PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH : - PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH; - break; - case PROPERTY_TYPES.JSON: - this.$scope.maxLength = PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH; - break; - default: - this.$scope.maxLength = PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH; - } - }; - - private initScope = ():void => { - this.$scope.forms = {}; - this.$scope.modalInstanceInput = this.$uibModalInstance; - this.$scope.inputEditModel = { - editInput: null - }; - this.$scope.inputEditModel.editInput = this.input; - this.initDefaultValueMaxLength(); - - //scope methods - this.$scope.save = ():void => { - if (this.$scope.showSchema()) { - this.$scope.inputEditModel.editInput.defaultValue = JSON.stringify(this.$scope.myValue); - } - }; - - this.$scope.close = ():void => { - this.$uibModalInstance.close(); - }; - - this.$scope.validateIntRange = (value:string):boolean => { - return !value || this.ValidationUtils.validateIntRange(value); - }; - - this.$scope.validateJson = (json:string):boolean => { - if (!json) { - return true; - } - return this.ValidationUtils.validateJson(json); - }; - - this.$scope.showSchema = ():boolean => { - return ['list', 'map'].indexOf(this.$scope.inputEditModel.editInput.type) > -1; - }; - - this.$scope.getValidationPattern = (type:string):RegExp => { - return this.ValidationUtils.getValidationPattern(type); - }; - - // Add the done button at the footer. - this.$scope.footerButtons = [ - {'name': 'Done', 'css': 'blue', 'callback': this.$scope.save}, - {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close} - ]; - - this.$scope.$watchCollection("forms.editForm.$invalid", (newVal, oldVal) => { - this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid; - }); - - }; -} - diff --git a/catalog-ui/src/app/view-models/forms/input-form/input-form-view.html b/catalog-ui/src/app/view-models/forms/input-form/input-form-view.html deleted file mode 100644 index 446a926ed4..0000000000 --- a/catalog-ui/src/app/view-models/forms/input-form/input-form-view.html +++ /dev/null @@ -1,141 +0,0 @@ - - - - -
    -
    - -
    - -
    - - -
    - - -
    - - -
    - - -
    - - -
    - -
    - -
    - - -
    - -
    - - -
    - -
    - -
    -
    - -
    -
    - -
    -
    -
    - - - -
    - - -
    -
    -
    -
    -
    - -
    - -
    - -
    -
    - -
    diff --git a/catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base-view.html b/catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base-view.html index e2594bc727..ae96b66641 100644 --- a/catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base-view.html +++ b/catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base-view.html @@ -13,7 +13,6 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> -
    diff --git a/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view-model.ts b/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view-model.ts index f5c057e41e..37b1ce75a8 100644 --- a/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view-model.ts +++ b/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view-model.ts @@ -20,12 +20,16 @@ 'use strict'; import * as _ from "lodash"; -import { - PROPERTY_TYPES, ModalsHandler, ValidationUtils, PROPERTY_VALUE_CONSTRAINTS, FormState, PROPERTY_DATA} from "app/utils"; -import {DataTypesService} from "app/services"; -import {PropertyModel, DataTypesMap, Component, GroupInstance, PolicyInstance, PropertyBEModel} from "app/models"; -import {ComponentInstance} from "../../../../models/componentsInstances/componentInstance"; +import { PROPERTY_TYPES, ValidationUtils, PROPERTY_VALUE_CONSTRAINTS, FormState, PROPERTY_DATA } from "app/utils"; +import { DataTypesService } from "app/services"; +import { PropertyModel, DataTypesMap, Component, GroupInstance, PolicyInstance, PropertyBEModel, ComponentMetadata } from "app/models"; +import { ComponentInstance } from "../../../../models/componentsInstances/componentInstance"; import { ComponentInstanceServiceNg2 } from "app/ng2/services/component-instance-services/component-instance.service"; +import { SdcUiCommon, SdcUiServices, SdcUiComponents } from "onap-ui-angular"; +import { CompositionService } from "app/ng2/pages/composition/composition.service"; +import { WorkspaceService } from "app/ng2/pages/workspace/workspace.service"; +import { Observable } from "rxjs"; +import { TopologyTemplateService } from "app/ng2/services/component-services/topology-template.service"; export interface IEditPropertyModel { property:PropertyModel; @@ -44,7 +48,7 @@ interface IPropertyFormViewModelScope extends ng.IScope { propertyNameValidationPattern:RegExp; commentValidationPattern:RegExp; editPropertyModel:IEditPropertyModel; - modalInstanceProperty:ng.ui.bootstrap.IModalServiceInstance; + modalInstanceProperty:ng.ui.bootstrap.IModalServiceInstance; currentPropertyIndex:number; isLastProperty:boolean; myValue:any; @@ -54,6 +58,7 @@ interface IPropertyFormViewModelScope extends ng.IScope { maxLength:number; isPropertyValueOwner:boolean; isVnfConfiguration:boolean; + constraints:string[]; validateJson(json:string):boolean; save(doNotCloseModal?:boolean):void; @@ -82,17 +87,20 @@ export class PropertyFormViewModel { 'PropertyNameValidationPattern', 'CommentValidationPattern', 'ValidationUtils', - 'component', + // 'component', '$filter', - 'ModalsHandler', + 'ModalServiceSdcUI', 'filteredProperties', '$timeout', 'isPropertyValueOwner', 'propertyOwnerType', 'propertyOwnerId', - 'ComponentInstanceServiceNg2' + 'ComponentInstanceServiceNg2', + 'TopologyTemplateService', + 'CompositionService', + 'workspaceService' ]; - + private formState:FormState; constructor(private $scope:IPropertyFormViewModelScope, @@ -103,17 +111,21 @@ export class PropertyFormViewModel { private PropertyNameValidationPattern:RegExp, private CommentValidationPattern:RegExp, private ValidationUtils:ValidationUtils, - private component:Component, + // private component:Component, private $filter:ng.IFilterService, - private ModalsHandler:ModalsHandler, + private modalService:SdcUiServices.ModalService, private filteredProperties:Array, private $timeout:ng.ITimeoutService, private isPropertyValueOwner:boolean, private propertyOwnerType:string, private propertyOwnerId:string, - private ComponentInstanceServiceNg2: ComponentInstanceServiceNg2) { + private ComponentInstanceServiceNg2: ComponentInstanceServiceNg2, + private topologyTemplateService: TopologyTemplateService, + private compositionService: CompositionService, + private workspaceService: WorkspaceService) { this.formState = angular.isDefined(property.name) ? FormState.UPDATE : FormState.CREATE; + this.initScope(); } @@ -121,8 +133,10 @@ export class PropertyFormViewModel { this.$scope.editPropertyModel.property = new PropertyModel(this.property); this.$scope.editPropertyModel.property.type = this.property.type ? this.property.type : null; this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.value || this.$scope.editPropertyModel.property.defaultValue; + this.$scope.constraints = this.property.constraints && this.property.constraints[0] ? this.property.constraints[0]["validValues"] : null; + this.setMaxLength(); - this.initAddOnLabels(); + }; //init property add-ons labels that show up at the left side of the input. @@ -131,23 +145,13 @@ export class PropertyFormViewModel { //the server sends back the normalized name. Remove it (to prevent interference with validation) and set the addon label to the component name directly. //Note: this cant be done in properties.ts because we dont have access to the component if (this.$scope.editPropertyModel.property.value) { - let splitProp = this.$scope.editPropertyModel.property.value.split(new RegExp(this.component.normalizedName + '.', "gi")); + let splitProp = this.$scope.editPropertyModel.property.value.split(new RegExp(this.workspaceService.metadata.normalizedName + '.', "gi")); this.$scope.editPropertyModel.property.value = splitProp.pop(); } - this.$scope.editPropertyModel.property.addOn = this.component.name; + this.$scope.editPropertyModel.property.addOn = this.workspaceService.metadata.name; } } - private initEditPropertyModel = ():void => { - this.$scope.editPropertyModel = { - property: null, - types: PROPERTY_DATA.TYPES, - simpleTypes: PROPERTY_DATA.SIMPLE_TYPES - }; - - this.initResource(); - }; - private initForNotSimpleType = ():void => { let property = this.$scope.editPropertyModel.property; this.$scope.isTypeDataType = this.DataTypesService.isDataTypeForPropertyType(this.$scope.editPropertyModel.property); @@ -195,20 +199,25 @@ export class PropertyFormViewModel { this.$scope.commentValidationPattern = this.CommentValidationPattern; this.$scope.isLoading = false; this.$scope.isNew = (this.formState === FormState.CREATE); - this.$scope.isService = this.component.isService(); + this.$scope.isService = this.workspaceService.metadata.isService(); this.$scope.modalInstanceProperty = this.$uibModalInstance; this.$scope.currentPropertyIndex = _.findIndex(this.filteredProperties, i=> i.name == this.property.name); this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1); this.$scope.dataTypes = this.DataTypesService.getAllDataTypes(); this.$scope.isPropertyValueOwner = this.isPropertyValueOwner; this.$scope.propertyOwnerType = this.propertyOwnerType; - this.initEditPropertyModel(); + + this.$scope.editPropertyModel = { + property : new PropertyModel(this.property), + types : PROPERTY_DATA.TYPES, + simpleTypes : PROPERTY_DATA.SIMPLE_TYPES}; //All simple types + //check if property of VnfConfiguration this.$scope.isVnfConfiguration = false; - if(this.propertyOwnerType == "component" && angular.isArray(this.component.componentInstances)) { + if(this.propertyOwnerType == "component" && angular.isArray(this.compositionService.componentInstances)) { - var componentPropertyOwner:ComponentInstance = this.component.componentInstances.find((ci:ComponentInstance) => { + var componentPropertyOwner:ComponentInstance = this.compositionService.componentInstances.find((ci:ComponentInstance) => { return ci.uniqueId === this.property.resourceInstanceUniqueId; }); if (componentPropertyOwner && componentPropertyOwner.componentName === 'vnfConfiguration') { @@ -219,6 +228,7 @@ export class PropertyFormViewModel { this.$scope.nonPrimitiveTypes = _.filter(Object.keys(this.$scope.dataTypes), (type:string)=> { return this.$scope.editPropertyModel.types.indexOf(type) == -1; }); + this.initResource(); this.initForNotSimpleType(); @@ -263,10 +273,10 @@ export class PropertyFormViewModel { //Not clean, but doing this as a temporary fix until we update the property right panel modals if(this.propertyOwnerType == "group"){ - this.ComponentInstanceServiceNg2.updateComponentGroupInstanceProperties(this.component, this.propertyOwnerId, [property]) + this.ComponentInstanceServiceNg2.updateComponentGroupInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property]) .subscribe((propertiesFromBE) => { onPropertySuccess(propertiesFromBE[0])}, error => onPropertyFaild); } else if(this.propertyOwnerType == "policy"){ - this.ComponentInstanceServiceNg2.updateComponentPolicyInstanceProperties(this.component, this.propertyOwnerId, [property]) + this.ComponentInstanceServiceNg2.updateComponentPolicyInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property]) .subscribe((propertiesFromBE) => { onPropertySuccess(propertiesFromBE[0])}, error => onPropertyFaild); } else { //in case we have uniqueId we call update method @@ -275,7 +285,7 @@ export class PropertyFormViewModel { let myValueString:string = JSON.stringify(this.$scope.myValue); property.value = myValueString; } - this.component.updateInstanceProperties(property.resourceInstanceUniqueId, [property]).then((propertiesFromBE) => onPropertySuccess(propertiesFromBE[0]), onPropertyFaild); + this.updateInstanceProperties(property.resourceInstanceUniqueId, [property]).subscribe((propertiesFromBE) => onPropertySuccess(propertiesFromBE[0]), onPropertyFaild); } else { if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) { let myValueString:string = JSON.stringify(this.$scope.myValue); @@ -283,7 +293,7 @@ export class PropertyFormViewModel { } else { this.$scope.editPropertyModel.property.defaultValue = this.$scope.editPropertyModel.property.value; } - this.component.addOrUpdateProperty(property).then(onPropertySuccess, onPropertyFaild); + this.addOrUpdateProperty(property).subscribe(onPropertySuccess, onPropertyFaild); } } }; @@ -362,14 +372,65 @@ export class PropertyFormViewModel { }; this.$scope.delete = (property:PropertyModel):void => { - let onOk = ():void => { - this.component.deleteProperty(property.uniqueId).then( + let onOk: Function = ():void => { + this.deleteProperty(property.uniqueId).subscribe( this.$scope.close ); }; let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE"); let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}"); - this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk); + const okButton = {testId: "OK", text: "OK", type: SdcUiCommon.ButtonType.info, callback: onOk, closeModal: true} as SdcUiComponents.ModalButtonComponent; + this.modalService.openInfoModal(title, message, 'delete-modal', [okButton]); }; } + + private updateInstanceProperties = (componentInstanceId:string, properties:PropertyModel[]):Observable => { + + return this.ComponentInstanceServiceNg2.updateInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, componentInstanceId, properties) + .map(newProperties => { + newProperties.forEach((newProperty) => { + if(newProperty.path[0] === newProperty.resourceInstanceUniqueId) newProperty.path.shift(); + // find exist instance property in parent component for update the new value ( find bu uniqueId & path) + let existProperty: PropertyModel = _.find(this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId], { + uniqueId: newProperty.uniqueId, + path: newProperty.path + }); + let index = this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId].indexOf(existProperty); + this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId][index] = newProperty; + }); + return newProperties; + }); + }; + + private addOrUpdateProperty = (property:PropertyModel):Observable => { + if (!property.uniqueId) { + let onSuccess = (property:PropertyModel):PropertyModel => { + let newProperty = new PropertyModel(property); + this.filteredProperties.push(newProperty); + return newProperty; + }; + return this.topologyTemplateService.addProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property).map(onSuccess); + } + else { + let onSuccess = (newProperty:PropertyModel):PropertyModel => { + // find exist instance property in parent component for update the new value ( find bu uniqueId ) + let existProperty:PropertyModel = _.find(this.filteredProperties, {uniqueId: newProperty.uniqueId}); + let propertyIndex = this.filteredProperties.indexOf(existProperty); + this.filteredProperties[propertyIndex] = newProperty; + return newProperty; + }; + return this.topologyTemplateService.updateProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property).map(onSuccess); + } + }; + + public deleteProperty = (propertyId:string):Observable => { + let onSuccess = ():void => { + console.log("Property deleted"); + delete _.remove(this.filteredProperties, {uniqueId: propertyId})[0]; + }; + let onFailed = ():void => { + console.log("Failed to delete property"); + }; + return this.topologyTemplateService.deleteProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, propertyId).map(onSuccess, onFailed); + }; } diff --git a/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view.html b/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view.html index 1f484160da..7c29d98641 100644 --- a/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view.html +++ b/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view.html @@ -13,7 +13,6 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> -
    @@ -160,8 +159,11 @@ fields-prefix-name="currentPropertyIndex" read-only="(editPropertyModel.property.readonly && !isPropertyValueOwner) || isVnfConfiguration" default-value="{{getDefaultValue()}}" - max-length="maxLength"> + max-length="maxLength" + constraints = "editPropertyModel.property.constraints && editPropertyModel.property.constraints[0].validValues"> +
    +
    + max-length="maxLength" + constraints = "editPropertyModel.property.constraints && editPropertyModel.property.constraints[0].validValues">
    +
    {{editPropertyModel.property.addOn}} + + + + + + - -
    - - - -
    - -
    - - - - - - - diff --git a/catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name.less b/catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name.less deleted file mode 100644 index 57698bef17..0000000000 --- a/catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name.less +++ /dev/null @@ -1,29 +0,0 @@ -.w-sdc-modal-resource-instance-name { - - .w-sdc-modal-body { - overflow: visible; - } - - .w-sdc-modal-action { - display: flex; - align-items: center; - justify-content: center; - } - - .w-sdc-modal-resource-instance-input { - .p_1; - border: solid 1px @color_p; - height: 45px; - padding: 0 20px; - margin: 0 auto 0 auto; - display: block; - } - .w-sdc-modal-body { - border-bottom: none; - } - - .w-sdc-form .i-sdc-form-item.error::after { - top: 13px; - } - -} diff --git a/catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal-view-model.ts b/catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal-view-model.ts deleted file mode 100644 index 7998d10623..0000000000 --- a/catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal-view-model.ts +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {ValidationUtils, ModalType} from "app/utils"; - -export interface IConfirmationModalModel { - title:string; - message:string; - showComment:boolean; - type:ModalType; -} - -interface IConfirmationModalViewModelScope { - modalInstanceConfirmation:ng.ui.bootstrap.IModalServiceInstance; - confirmationModalModel:IConfirmationModalModel; - comment:any; - commentValidationPattern:RegExp; - editForm:ng.IFormController; - okButtonColor:string; - hideCancelButton:boolean; - ok():any; - cancel():void; -} - -export class ConfirmationModalViewModel { - - static '$inject' = ['$scope', '$uibModalInstance', 'confirmationModalModel', 'CommentValidationPattern', 'ValidationUtils']; - - constructor(private $scope:IConfirmationModalViewModelScope, - private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance, - confirmationModalModel:IConfirmationModalModel, - private CommentValidationPattern:RegExp, - private ValidationUtils:ValidationUtils) { - - this.initScope(confirmationModalModel); - } - - private initScope = (confirmationModalModel:IConfirmationModalModel):void => { - let self = this; - this.$scope.hideCancelButton = false; - this.$scope.modalInstanceConfirmation = this.$uibModalInstance; - this.$scope.confirmationModalModel = confirmationModalModel; - this.$scope.comment = {"text": ''}; - this.$scope.commentValidationPattern = this.CommentValidationPattern; - - this.$scope.ok = ():any => { - self.$uibModalInstance.close(this.ValidationUtils.stripAndSanitize(self.$scope.comment.text)); - }; - - this.$scope.cancel = ():void => { - console.info('Cancel pressed on: ' + this.$scope.confirmationModalModel.title); - self.$uibModalInstance.dismiss(); - }; - - // Set the OK button color according to modal type (standard, error, alert) - let _okButtonColor = 'blue'; // Default - switch (confirmationModalModel.type) { - case ModalType.STANDARD: - _okButtonColor = 'blue'; - break; - case ModalType.ERROR: - _okButtonColor = 'red'; - break; - case ModalType.ALERT: - this.$scope.hideCancelButton = true; - _okButtonColor = 'grey'; - break; - default: - _okButtonColor = 'blue'; - break; - } - this.$scope.okButtonColor = _okButtonColor; - - } -} diff --git a/catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal-view.html b/catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal-view.html deleted file mode 100644 index cb9b159e51..0000000000 --- a/catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal-view.html +++ /dev/null @@ -1,45 +0,0 @@ - - - -
    - - -
    - - -
    - - -
    -
    -
    - -
    diff --git a/catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal.less b/catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal.less deleted file mode 100644 index 666c41d5ed..0000000000 --- a/catalog-ui/src/app/view-models/modals/confirmation-modal/confirmation-modal.less +++ /dev/null @@ -1,30 +0,0 @@ -.w-sdc-modal-confirmation { - form.w-sdc-form{ - padding: 0; - } - - .w-sdc-modal-body-content { - .b_6; - word-break: break-word; - - } - .w-sdc-modal-body { - height: auto; - /* padding: 47px 60px 20px 60px; */ - border-bottom: none; - } - .w-sdc-modal-body-content { - padding: 0; - } - .w-sdc-modal-body-comment { - width: 430px; - height: 127px; - border: solid 1px @color_e; - margin: 20px 0 0 0; - padding: 15px; - } - .w-sdc-modal-label { - .m_14_r; - text-align: left; - } -} diff --git a/catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal-view-model.ts b/catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal-view-model.ts deleted file mode 100644 index 45696568b4..0000000000 --- a/catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal-view-model.ts +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; - -export interface IConformanceLevelModalModelScope { - footerButtons:Array; - modalInstance:ng.ui.bootstrap.IModalServiceInstance; -} - -export class ConformanceLevelModalViewModel { - - static '$inject' = ['$scope', '$uibModalInstance']; - - constructor(private $scope:IConformanceLevelModalModelScope, - private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance) { - - this.initScope(); - } - - private initScope = ():void => { - - this.$scope.modalInstance = this.$uibModalInstance; - - this.$scope.footerButtons = [ - {'name': 'Continue', 'css': 'grey', 'callback': this.$uibModalInstance.close}, - {'name': 'Reject', 'css': 'blue', 'callback': this.$uibModalInstance.dismiss} - ]; - - }; - -} diff --git a/catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal-view.html b/catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal-view.html deleted file mode 100644 index 5ba0425ea2..0000000000 --- a/catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal-view.html +++ /dev/null @@ -1,38 +0,0 @@ - - - - - -
    -

    - You are about to distribute a service with models and artifacts created with an older version of the platform. - For such service, new properties, metadata and requirements needed by ECOMP components will not be available. -

    - It is highly recommended that you upgrade the service models and artifacts. -

    - Click "Continue" if you need to distribute the current service version.
    - Click "Reject" if you need to stop the distribution and manually upgrade the service. -

    -
    -
    - -
    diff --git a/catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal.less b/catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal.less deleted file mode 100644 index 7f195ade83..0000000000 --- a/catalog-ui/src/app/view-models/modals/conformance-level-modal/conformance-level-modal.less +++ /dev/null @@ -1,3 +0,0 @@ -.conformance-level-modal{ - -} diff --git a/catalog-ui/src/app/view-models/modals/email-modal/email-modal-view-model.ts b/catalog-ui/src/app/view-models/modals/email-modal/email-modal-view-model.ts deleted file mode 100644 index 095d1438b2..0000000000 --- a/catalog-ui/src/app/view-models/modals/email-modal/email-modal-view-model.ts +++ /dev/null @@ -1,116 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {IAppConfigurtaion, Component, AsdcComment} from "app/models"; -import {ValidationUtils} from "app/utils"; - -export interface IEmailModalModel_Email { - to:string; - subject:string; - message:string; -} - -export interface IEmailModalModel_Data { - component:Component; - stateUrl:string; -} - -export interface IEmailModalModel { - title:string; - email:IEmailModalModel_Email; - data:IEmailModalModel_Data; -} - -interface IEmailModalViewModelScope { - modalInstanceEmail:ng.ui.bootstrap.IModalServiceInstance; - emailModalModel:IEmailModalModel; - submitInProgress:boolean; - commentValidationPattern:RegExp; - isLoading:boolean; - submit():any; - cancel():void; - validateField(field:any):boolean; -} - -export class EmailModalViewModel { - - static '$inject' = ['$scope', '$filter', 'sdcConfig', '$uibModalInstance', 'emailModalModel', 'ValidationUtils', 'CommentValidationPattern']; - - constructor(private $scope:IEmailModalViewModelScope, - private $filter:ng.IFilterService, - private sdcConfig:IAppConfigurtaion, - private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance, - private emailModalModel:IEmailModalModel, - private ValidationUtils:ValidationUtils, - private CommentValidationPattern:RegExp) { - - this.initScope(emailModalModel); - } - - private initScope = (emailModalModel:IEmailModalModel):void => { - this.$scope.emailModalModel = emailModalModel; - this.$scope.submitInProgress = false; - this.$scope.commentValidationPattern = this.CommentValidationPattern; - this.$scope.modalInstanceEmail = this.$uibModalInstance; - - this.$scope.submit = ():any => { - - let onSuccess = (component:Component) => { - this.$scope.isLoading = false; - this.$scope.submitInProgress = false; - // showing the outlook modal according to the config json - if (this.sdcConfig.showOutlook) { - let link:string = encodeURI(this.sdcConfig.api.baseUrl + "?folder=Ready_For_Testing"); - let outlook:string = this.$filter('translate')("EMAIL_OUTLOOK_MESSAGE", "{'to': '" + emailModalModel.email.to + "','subject': '" + emailModalModel.email.subject + "','message': '" + emailModalModel.email.message + "', 'entityNameAndVersion': '" + emailModalModel.email.subject + "','link': '" + link + "'}"); - window.location.href = outlook; // Open outlook with the email to send - } - this.$uibModalInstance.close(component); // Close the dialog - }; - - let onError = () => { - this.$scope.isLoading = false; - this.$scope.submitInProgress = false; - this.$uibModalInstance.close(); // Close the dialog - }; - - // Submit to server - // Prevent from user pressing multiple times on submit. - if (this.$scope.submitInProgress === false) { - this.$scope.isLoading = true; - this.$scope.submitInProgress = true; - let comment:AsdcComment = new AsdcComment(); - comment.userRemarks = emailModalModel.email.message; - emailModalModel.data.component.changeLifecycleState(emailModalModel.data.stateUrl, comment).then(onSuccess, onError); - } - }; - - this.$scope.cancel = ():void => { - this.$uibModalInstance.dismiss(); - }; - - this.$scope.validateField = (field:any):boolean => { - if (field && field.$dirty && field.$invalid) { - return true; - } - return false; - }; - } -} diff --git a/catalog-ui/src/app/view-models/modals/email-modal/email-modal-view.html b/catalog-ui/src/app/view-models/modals/email-modal/email-modal-view.html deleted file mode 100644 index 612fe226aa..0000000000 --- a/catalog-ui/src/app/view-models/modals/email-modal/email-modal-view.html +++ /dev/null @@ -1,93 +0,0 @@ - - - diff --git a/catalog-ui/src/app/view-models/modals/email-modal/email-modal.less b/catalog-ui/src/app/view-models/modals/email-modal/email-modal.less deleted file mode 100644 index 471089fa1a..0000000000 --- a/catalog-ui/src/app/view-models/modals/email-modal/email-modal.less +++ /dev/null @@ -1,57 +0,0 @@ -.w-sdc-modal-email { - - .w-sdc-modal-body { - border-bottom: none; - } - - form.w-sdc-form{ - padding: 0; - - .i-sdc-form-item { - clear: both; - label { - min-height: 30px; - padding-top: 4px; - } - - .col-sm-10 { - padding-right: 0; - } - - } - - .w-sdc-modal-body-email { - border-style: solid; - border-width: 1px; - border-color: @color_e; - box-sizing: border-box; - width: 100%; - height: 127px; - margin-bottom: 20px; - } - - label {.m_14_m; text-align: left;} - input {.m_14_r;} - textarea {.m_14_r;} - /* I made the subject and to fields as input (for future use), but for now they look like labels: */ - input:disabled { - .bg_c; - border: none; - } - } - - .w-sdc-modal-action { - background-color: @main_color_p; - padding: 0 13px 0 0; - height: 90px; - line-height: 65px; - - button {width: 174px;} - } - - .w-sdc-form .i-sdc-form-item label.required::before { - position: absolute; - left: -13px; - } - -} diff --git a/catalog-ui/src/app/view-models/modals/error-modal/error-403-view.html b/catalog-ui/src/app/view-models/modals/error-modal/error-403-view.html index ba08b51fa3..1cab8adb3b 100644 --- a/catalog-ui/src/app/view-models/modals/error-modal/error-403-view.html +++ b/catalog-ui/src/app/view-models/modals/error-modal/error-403-view.html @@ -13,7 +13,6 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> -
    diff --git a/catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.html b/catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.html index 75bc82dcfd..86c776a7ee 100644 --- a/catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.html +++ b/catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.html @@ -13,7 +13,6 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> -
    diff --git a/catalog-ui/src/app/view-models/modals/message-modal/message-base-modal-model.ts b/catalog-ui/src/app/view-models/modals/message-modal/message-base-modal-model.ts deleted file mode 100644 index b987f1088e..0000000000 --- a/catalog-ui/src/app/view-models/modals/message-modal/message-base-modal-model.ts +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {SEVERITY} from "app/utils"; - -export interface IMessageModalModel { - title:string; - message:string; - severity:SEVERITY; -} - -export interface IMessageModalViewModelScope extends ng.IScope { - footerButtons:Array; - messageModalModel:IMessageModalModel; - modalInstanceError:ng.ui.bootstrap.IModalServiceInstance; - ok():void; -} - -export class MessageModalViewModel { - - constructor(private $baseScope:IMessageModalViewModelScope, - private $baseModalInstance:ng.ui.bootstrap.IModalServiceInstance, - private baseMessageModalModel:IMessageModalModel) { - - this.initScope(baseMessageModalModel); - } - - private initScope = (messageModalViewModel:IMessageModalModel):void => { - - this.$baseScope.messageModalModel = messageModalViewModel; - this.$baseScope.modalInstanceError = this.$baseModalInstance; - - this.$baseScope.ok = ():void => { - this.$baseModalInstance.close(); - }; - - this.$baseScope.footerButtons = [ - { - 'name': 'OK', - 'css': 'grey', - 'callback': this.$baseScope.ok - } - ]; - } -} diff --git a/catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal-view-model.ts b/catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal-view-model.ts deleted file mode 100644 index f2b2217645..0000000000 --- a/catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal-view-model.ts +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {IMessageModalModel, MessageModalViewModel, IMessageModalViewModelScope} from "../message-base-modal-model"; - -export interface IClientMessageModalModel extends IMessageModalModel { -} - -export interface IClientMessageModalViewModelScope extends IMessageModalViewModelScope { - clientMessageModalModel:IClientMessageModalModel; -} - -export class ClientMessageModalViewModel extends MessageModalViewModel { - - static '$inject' = ['$scope', '$uibModalInstance', 'clientMessageModalModel']; - - constructor(private $scope:IClientMessageModalViewModelScope, - private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance, - private clientMessageModalModel:IClientMessageModalModel) { - - super($scope, $uibModalInstance, clientMessageModalModel); - } - -} diff --git a/catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal-view.html b/catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal-view.html deleted file mode 100644 index f0a4f9a8db..0000000000 --- a/catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal-view.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - -
    -
    -
    -
    - -
    - -
    diff --git a/catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal.less b/catalog-ui/src/app/view-models/modals/message-modal/message-client-modal/client-message-modal.less deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal-view-model.ts b/catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal-view-model.ts deleted file mode 100644 index b92069fce2..0000000000 --- a/catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal-view-model.ts +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {IMessageModalModel, IMessageModalViewModelScope, MessageModalViewModel} from "../message-base-modal-model"; - -export interface IServerMessageModalModel extends IMessageModalModel { - status:string; - messageId:string; - - -} - -export interface IServerMessageModalViewModelScope extends IMessageModalViewModelScope { - serverMessageModalModel:IServerMessageModalModel; -} - -export class ServerMessageModalViewModel extends MessageModalViewModel { - - static '$inject' = ['$scope', '$uibModalInstance', 'serverMessageModalModel']; - - constructor(private $scope:IServerMessageModalViewModelScope, - private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance, - private serverMessageModalModel:IServerMessageModalModel) { - - super($scope, $uibModalInstance, serverMessageModalModel); - } - -} diff --git a/catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal-view.html b/catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal-view.html deleted file mode 100644 index 7d3204c095..0000000000 --- a/catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal-view.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - -
    -
    -
    Error code: {{messageModalModel.messageId}}
    -
    Status code: {{messageModalModel.status}}
    -
    -
    -
    - -
    diff --git a/catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal.less b/catalog-ui/src/app/view-models/modals/message-modal/message-server-modal/server-message-modal.less deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal-view-model.ts b/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal-view-model.ts deleted file mode 100644 index 01394a3c33..0000000000 --- a/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal-view-model.ts +++ /dev/null @@ -1,272 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {ComponentType, SEVERITY, FileUtils, ModalsHandler, ComponentFactory} from "app/utils"; -import {OnboardingService, CacheService} from "app/services"; -import {Component, IComponent, IUser, IAppConfigurtaion, Resource} from "app/models"; -import {IServerMessageModalModel} from "../message-modal/message-server-modal/server-message-modal-view-model"; -import {Dictionary} from "app/utils"; -import * as _ from 'underscore'; - -interface IOnboardingModalViewModelScope { - modalOnboarding:ng.ui.bootstrap.IModalServiceInstance; - componentsList:Array; - tableHeadersList:Array; - selectedComponent:Component; - componentFromServer:Component; - reverse:boolean; - sortBy:string; - searchBind:string; - okButtonText:string; - isCsarComponentExists:boolean; - user:IUser; - isLoading:boolean; - - //this is for UI paging - numberOfItemsToDisplay:number; - allItemsDisplayed:boolean; - - doSelectComponent(component:Component):void; - doUpdateCsar():void; - doImportCsar():void; - sort(sortBy:string):void; - downloadCsar(packageId:string):void; - increaseNumItemsToDisplay():void; -} - -export class OnboardingModalViewModel { - - static '$inject' = [ - '$scope', - '$filter', - '$state', - 'sdcConfig', - '$uibModalInstance', - 'Sdc.Services.OnboardingService', - 'okButtonText', - 'currentCsarUUID', - 'currentCsarVersion', - 'Sdc.Services.CacheService', - 'FileUtils', - 'ComponentFactory', - 'ModalsHandler' - ]; - - constructor(private $scope:IOnboardingModalViewModelScope, - private $filter:ng.IFilterService, - private $state:any, - private sdcConfig:IAppConfigurtaion, - private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance, - private onBoardingService:OnboardingService, - private okButtonText:string, - private currentCsarUUID:string, - private currentCsarVersion:string, - private cacheService:CacheService, - private fileUtils:FileUtils, - private componentFactory:ComponentFactory, - private modalsHandler:ModalsHandler) { - - this.init(); - } - - /** - * Called from controller constructor, this will call onboarding service to get list - * of "mini" components (empty components created from CSAR). - * The list is inserted to componentsList on $scope. - * And then call initScope method. - */ - private init = ():void => { - this.initOnboardingComponentsList(); - }; - - private initScope = ():void => { - - this.initSortedTableScope(); - this.initModalScope(); - this.$scope.sortBy = "name"; // Default sort by - this.$scope.user = this.cacheService.get('user'); - this.$scope.okButtonText = this.okButtonText; - this.$scope.numberOfItemsToDisplay = 0; - this.$scope.allItemsDisplayed = false; - - // Dismiss the modal and pass the "mini" component to workspace general page - this.$scope.doImportCsar = ():void => { - - this.$uibModalInstance.close({ - componentCsar: this.$scope.selectedComponent, - type: ComponentType.RESOURCE.toLowerCase() - }); - }; - - this.$scope.doUpdateCsar = ():void => { - - // Change the component version to the CSAR version we want to update. - if(!this.currentCsarVersion || this.currentCsarVersion != (this.$scope.selectedComponent).csarVersion) { - this.$uibModalInstance.close({ - componentCsar: this.$scope.selectedComponent, - previousComponent: this.$scope.componentFromServer, - type: this.$scope.componentFromServer.componentType.toLowerCase() - - }); - - } else { - this.$uibModalInstance.close(); - } - }; - - this.$scope.downloadCsar = (packageId:string):void => { - this.$scope.isLoading = true; - this.onBoardingService.downloadOnboardingCsar(packageId).then( - (file:any):void => { - this.$scope.isLoading = false; - if (file) { - this.fileUtils.downloadFile(file, packageId + '.csar'); - } - }, ():void => { - this.$scope.isLoading = false; - var data:IServerMessageModalModel = { - title: 'Download error', - message: "Error downloading file", - severity: SEVERITY.ERROR, - messageId: "", - status: "" - }; - this.modalsHandler.openServerMessageModal(data); - } - ); - }; - - this.$scope.increaseNumItemsToDisplay = ():void => { - this.$scope.numberOfItemsToDisplay = this.$scope.numberOfItemsToDisplay + 40; - if (this.$scope.componentsList) { - this.$scope.allItemsDisplayed = this.$scope.numberOfItemsToDisplay >= this.$scope.componentsList.length; - } - }; - - // When the user select a row, set the component as selectedComponent - this.$scope.doSelectComponent = (component:Component):void => { - - if (this.$scope.selectedComponent === component) { - // Collapse the item - this.$scope.selectedComponent = undefined; - return; - } - - this.$scope.isLoading = true; - this.$scope.componentFromServer = undefined; - this.$scope.selectedComponent = component; - - let onSuccess = (componentFromServer:Component):void => { - this.$scope.isLoading = false; - if (componentFromServer) { - this.$scope.componentFromServer = componentFromServer; - this.$scope.isCsarComponentExists = true; - } else { - this.$scope.componentFromServer = component; - this.$scope.isCsarComponentExists = false; - } - }; - - let onError = ():void => { - this.$scope.isLoading = false; - this.$scope.componentFromServer = component; - this.$scope.isCsarComponentExists = false; - }; - - this.onBoardingService.getComponentFromCsarUuid((component).csarUUID).then(onSuccess, onError); - }; - - }; - - private initSortedTableScope = ():void => { - this.$scope.tableHeadersList = [ - {title: 'Name', property: 'name'}, - {title: 'Vendor', property: 'vendorName'}, - {title: 'Category', property: 'categories'}, - {title: 'Version', property: 'csarVersion'}, - {title: 'Type', property: 'resourceType'}, - {title: '#', property: 'importAndUpdate'} - //{title: 'Date', property: 'componentDate'} - ]; - - this.$scope.sort = (sortBy:string):void => { - this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false; - this.$scope.sortBy = sortBy; - }; - }; - - private initModalScope = ():void => { - // Enable the modal directive to close - this.$scope.modalOnboarding = this.$uibModalInstance; - }; - - private initOnboardingComponentsList = ():void => { - let onSuccess = (onboardingResponse:Array):void => { - initMaxVersionOfItemsInList(onboardingResponse); - - if (this.currentCsarUUID) { - //this.$scope.componentsList = this.$filter('filter')(this.$scope.componentsList, {csarUUID: this.currentCsarUUID}); - this.$scope.componentsList = this.$filter('filter')(this.$scope.componentsList, - (input):boolean => { - return input.csarUUID === this.currentCsarUUID; - } - ); - } - this.initScope(); - }; - - let onError = ():void => { - console.log("Error getting onboarding list"); - this.initScope(); - }; - - let initMaxVersionOfItemsInList = (onboardingResponse:Array):void => { - // Get only the latest version of each item - this.$scope.componentsList = []; - - // Get all unique items from the list - let uniqueItems:Array = _.uniq(onboardingResponse, false, (item:any):void=>{ - return item.packageId; - }); - - // Loop on all the items with unique packageId - _.each(uniqueItems, (item:any):void=> { - // Find all the items that has same packageId - let ItemsFound:Array = _.filter(onboardingResponse, (inListItem:any):any => { - return inListItem.packageId === item.packageId; - }); - - // Loop on all the items with same packageId and find the max version. - let maxItem:any; - _.each(ItemsFound, (ItemFound:any):void=> { - if (!maxItem) { - maxItem = ItemFound; - } else if (maxItem && parseInt(maxItem.csarVersion) < parseInt(ItemFound.csarVersion)) { - maxItem = ItemFound; - } - }); - this.$scope.componentsList.push(maxItem); - }); - }; - - this.onBoardingService.getOnboardingComponents().then(onSuccess, onError); - }; -} diff --git a/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal-view.html b/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal-view.html deleted file mode 100644 index 7f19389bdf..0000000000 --- a/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal-view.html +++ /dev/null @@ -1,165 +0,0 @@ - - - - -
    -
    -

    Select one of the software product component below:

    -
    - - -
    - -
    -
    - - -
    -
    {{header.title}} - -
    -
    - - -
    - - - -
    - There are no software product component to display -
    - -
    - - -
    - - -
    - - {{component.name}} -
    - - -
    - {{component.vendorName}} -
    - - -
    - {{component.categories[0].name}} {{component.categories[0].subcategories[0].name}} -
    - - -
    - {{component.csarVersion}} -
    - - -
    - {{component.resourceType}} -
    - - -
    - -
    - -
    - -
    -
    VSP Description:
    - {{component.description}} -
    - -
    -
    - -
    Name: {{componentFromServer.name}}
    -
    Lifecycle: {{componentFromServer.lifecycleState}}
    -
    Creator: {{componentFromServer.creatorFullName}}
    -
    -
    - -
    -
    - -
    UUID: {{componentFromServer.uuid}}
    -
    Version: {{componentFromServer.version}}
    -
    Modifier: {{componentFromServer.lastUpdaterFullName}}
    -
    - Designers cannot update a VSP if the VF is checked out by another user. -
    -
    - Designers cannot update a VSP if the VF is in Ready for testing state. -
    -
    -
    - -
    - -
    - -
    - - - - - -
    - -
    -
    - -
    -
    -
    -
    - - -
    diff --git a/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal.less b/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal.less deleted file mode 100644 index ccf4fb00b5..0000000000 --- a/catalog-ui/src/app/view-models/modals/onboarding-modal/onboarding-modal.less +++ /dev/null @@ -1,149 +0,0 @@ -.w-sdc-modal-onboarding { - - width: 100%; - display: inline-block; - - .general-info-button{ - position: relative; - top: -40px; - left: 95px; - float: left; - } - - .title-wrapper { - display: flex; - justify-content: space-between; - align-items: flex-end; - - .sub-title { - .m_14_r; - float:left; - } - } - - .w-sdc-classic-btn { - float: right; - margin-bottom: 10px; - } - - .table{ - height: 472px; - margin-bottom: 0; - } - - .table-container-flex { - margin-top: 10px; - - .table { - .body { - .data-row + div.item-opened { - word-wrap: break-word; - display: flex; - justify-content: space-between; - padding: 10px 0; - - .item-opened-description-title, - .item-opened-metadata-title { - .m_14_m; - } - - .item-opened-description, - .item-opened-metadata1, - .item-opened-metadata2, - .item-opened-metadata3 { - .th { .m_14_m; } - flex-basis: 0; - overflow: hidden; - padding: 5px 15px; - } - - .item-opened-description, - .item-opened-metadata3 { - border-right: 1px solid @main_color_o; - } - - .item-opened-metadata2 { - word-break: break-word; - .note { - color: @func_color_q; - } - } - - .item-opened-icon { - flex-basis: 0; - overflow: hidden; - padding: 5px 15px; - align-self: center; - } - - .item-opened-description {flex-grow: 25.3;} - .item-opened-metadata1 {flex-grow: 25;} - .item-opened-metadata2 {flex-grow: 45;} - .item-opened-metadata3 { - flex-grow: 10; - .info-button{ - float: right; - } - } - .item-opened-icon {flex-grow: 10.1;} - } - } - } - - .flex-item:nth-child(1) { - flex-grow: 25; - .hand; - span.table-arrow { - margin-right: 7px; - } - } - - .flex-item:nth-child(2) {flex-grow: 25;} - .flex-item:nth-child(3) {flex-grow: 30;} - .flex-item:nth-child(4) {flex-grow: 10; text-align: center; } - .flex-item:nth-child(5) {flex-grow: 10; text-align: center; } - .flex-item:nth-child(6) {flex-grow: 10; } - - } - - .download-file-btn { - cursor: pointer; - margin-left: 4px; - } - - .refresh-file-btn, - .import-file-btn { - cursor: pointer; - margin-left: 20px; - } - - .top-search { - float: right; - position: relative; - - input.search-text { - .border-radius(2px); - width: 245px; - height: 32px; - line-height: 32px; - border: 1px solid @main_color_o; - margin: 0; - outline: none; - text-indent: 10px; - - &::-webkit-input-placeholder { font-style: italic; } /* Safari, Chrome and Opera */ - &:-moz-placeholder { font-style: italic; } /* Firefox 18- */ - &::-moz-placeholder { font-style: italic; } /* Firefox 19+ */ - &:-ms-input-placeholder { font-style: italic; } /* IE 10+ */ - &:-ms-input-placeholder { font-style: italic; } /* Edge */ - } - - .magnification { - position: absolute; - top: 10px; - right: 10px; - } - - } - -} diff --git a/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view-model.ts b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view-model.ts index 10f41f6b61..fc3672cc50 100644 --- a/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view-model.ts +++ b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view-model.ts @@ -22,7 +22,7 @@ import * as _ from "underscore"; import {IUserProperties} from "app/models"; import {MenuItemGroup, MenuItem} from "app/utils"; -import {CacheService} from "app/services"; +import {CacheService} from "app/services-ng2"; declare var PunchOutRegistry; export class BreadcrumbsMenuItem { diff --git a/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view.html b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view.html index fc1140ebf0..2d8010bd37 100644 --- a/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view.html +++ b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view.html @@ -13,7 +13,6 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> -
    diff --git a/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor.less b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor.less index 71a3101412..1e091e957d 100644 --- a/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor.less +++ b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor.less @@ -76,22 +76,6 @@ } } - &.READY_FOR_CERTIFICATION { - .i-sdc-categories-list-item-icon { - background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -2985px; - width: 14px; - height: 16px; - } - } - - &.CERTIFICATION_IN_PROGRESS { - .i-sdc-categories-list-item-icon { - background: url('/assets/styles/images/sprites/sprite-global-old.png') no-repeat -53px -2934px; - width: 14px; - height: 16px; - } - } - &.DISTRIBUTED, &.TBD { .i-sdc-categories-list-item-icon { diff --git a/catalog-ui/src/app/view-models/plugins/plugins-tab-view-model.ts b/catalog-ui/src/app/view-models/plugins/plugins-tab-view-model.ts deleted file mode 100644 index d25cd19bff..0000000000 --- a/catalog-ui/src/app/view-models/plugins/plugins-tab-view-model.ts +++ /dev/null @@ -1,83 +0,0 @@ -/* - -* Copyright (c) 2018 AT&T Intellectual Property. - -* - -* Licensed under the Apache License, Version 2.0 (the "License"); - -* you may not use this file except in compliance with the License. - -* You may obtain a copy of the License at - -* - -* http://www.apache.org/licenses/LICENSE-2.0 - -* - -* Unless required by applicable law or agreed to in writing, software - -* distributed under the License is distributed on an "AS IS" BASIS, - -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -* See the License for the specific language governing permissions and - -* limitations under the License. - -*/ - -import {IUserProperties, Plugin} from "app/models"; -import {CacheService} from "app/services"; -import {PluginsService} from "../../ng2/services/plugins.service"; - - -interface IPluginsTabViewModelScope extends ng.IScope { - plugin: Plugin - user: IUserProperties; - version: string; - queryParams: Object; - isLoading: boolean; - - onLoadingDone(plugin: Plugin): void; -} - -export class PluginsTabViewModel { - static '$inject' = [ - '$scope', - '$stateParams', - 'Sdc.Services.CacheService', - 'PluginsService' - ]; - - constructor(private $scope: IPluginsTabViewModelScope, - private $stateParams: any, - private cacheService: CacheService, - private pluginsService: PluginsService) { - - this.initScope(); - } - - private initScope = (): void => { - this.$scope.plugin = this.pluginsService.getPluginByStateUrl(this.$stateParams.path); - this.$scope.version = this.cacheService.get('version'); - this.$scope.user = this.cacheService.get('user'); - - this.$scope.isLoading = true; - - this.$scope.queryParams = { - userId: this.$scope.user.userId, - userRole: this.$scope.user.role, - displayType: "tab", - parentUrl: window.location.origin, - eventsClientId: this.$scope.plugin.pluginId - }; - - this.$scope.onLoadingDone = (plugin: Plugin) => { - if (plugin.pluginId == this.$scope.plugin.pluginId) { - this.$scope.isLoading = false; - } - }; - } -} diff --git a/catalog-ui/src/app/view-models/plugins/plugins-tab-view.html b/catalog-ui/src/app/view-models/plugins/plugins-tab-view.html deleted file mode 100644 index 50c5766625..0000000000 --- a/catalog-ui/src/app/view-models/plugins/plugins-tab-view.html +++ /dev/null @@ -1,21 +0,0 @@ - - -
    - - - -
    diff --git a/catalog-ui/src/app/view-models/preloading/preloading-view.html b/catalog-ui/src/app/view-models/preloading/preloading-view.html deleted file mode 100644 index e894587fdc..0000000000 --- a/catalog-ui/src/app/view-models/preloading/preloading-view.html +++ /dev/null @@ -1,25 +0,0 @@ - - -
    -

    -

    - -
    -
    Loading...
    -
    - -
    diff --git a/catalog-ui/src/app/view-models/preloading/preloading-view.ts b/catalog-ui/src/app/view-models/preloading/preloading-view.ts deleted file mode 100644 index d629d298f2..0000000000 --- a/catalog-ui/src/app/view-models/preloading/preloading-view.ts +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; - -interface IPreLoadingViewScope { - startZoomIn:boolean; -} - -export class PreLoadingViewModel { - - static '$inject' = ['$scope']; - - constructor(private $scope:IPreLoadingViewScope) { - this.init($scope); - } - - private init = ($scope:IPreLoadingViewScope):void => { - this.animate($('.caption1'), 'fadeInUp', 400); - this.animate($('.caption2'), 'fadeInUp', 800); - }; - - private animate = (element:any, animation:string, when:number):void => { - window.setTimeout(()=> { - element.addClass("animated " + animation); - element[0].style = "visibility: visible;"; - }, when); - }; - -} diff --git a/catalog-ui/src/app/view-models/shared/notification-custom-template.html b/catalog-ui/src/app/view-models/shared/notification-custom-template.html index 869c49bacf..9456b87093 100644 --- a/catalog-ui/src/app/view-models/shared/notification-custom-template.html +++ b/catalog-ui/src/app/view-models/shared/notification-custom-template.html @@ -13,7 +13,6 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> -
    diff --git a/catalog-ui/src/assets/styles/notification-template.less b/catalog-ui/src/app/view-models/shared/notification-template.less similarity index 100% rename from catalog-ui/src/assets/styles/notification-template.less rename to catalog-ui/src/app/view-models/shared/notification-template.less diff --git a/catalog-ui/src/app/view-models/support/support-view-model.ts b/catalog-ui/src/app/view-models/support/support-view-model.ts deleted file mode 100644 index 5703a74e97..0000000000 --- a/catalog-ui/src/app/view-models/support/support-view-model.ts +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {CacheService} from "app/services"; - -interface ISupportViewModelScope { - version:string; -} - -export class SupportViewModel { - - static '$inject' = ['$scope', 'Sdc.Services.CacheService']; - - constructor(private $scope:ISupportViewModelScope, - private cacheService:CacheService) { - this.$scope.version = this.cacheService.get('version'); - } -} diff --git a/catalog-ui/src/app/view-models/support/support-view.html b/catalog-ui/src/app/view-models/support/support-view.html deleted file mode 100644 index e85373b79d..0000000000 --- a/catalog-ui/src/app/view-models/support/support-view.html +++ /dev/null @@ -1,47 +0,0 @@ - - -
    - -
    - -
    Support
    - -
    -
    -
    -
    -
    In Design ({{numOfCheckOutEntities+numOfCheckInEntities}})
    -
    Checked Out ({{numOfCheckOutEntities}})
    -
    Checked In ({{numOfCheckInEntities}})
    -
    -
    -
    Completed Design ({{numOfReadyForCertificationEntities+numOfCertificationInProgressEntities+numOfCertifiedEntities}})
    -
    Ready For Certification ({{numOfReadyForCertificationEntities}})
    -
    Certification In Progress ({{numOfCertificationInProgressEntities}})
    -
    Certified ({{numOfCertifiedEntities}})
    -
    -
    -
    Catalog
    -
    Support
    -
    -
    -
    -
    diff --git a/catalog-ui/src/app/view-models/support/support.less b/catalog-ui/src/app/view-models/support/support.less deleted file mode 100644 index 8159e38320..0000000000 --- a/catalog-ui/src/app/view-models/support/support.less +++ /dev/null @@ -1,8 +0,0 @@ -.w-sdc-left-sidebar-in-progress, -.w-sdc-left-sidebar-following { - .b_7; -} - -.w-sdc-left-sidebar-following { - padding: 13px 0; -} diff --git a/catalog-ui/src/app/view-models/tabs/general-tab.less b/catalog-ui/src/app/view-models/tabs/general-tab.less deleted file mode 100644 index 936b3e3414..0000000000 --- a/catalog-ui/src/app/view-models/tabs/general-tab.less +++ /dev/null @@ -1,122 +0,0 @@ -.sdc-general-tab { - - display: flex; - min-height: 100%; - flex-flow: column; - - .sdc-edit-icon { - .sprite; - .e-sdc-small-icon-pencil; - } - .sdc-general-tab-title { - - .f-color.a; - .f-type._14_m; - padding: 0px 0px 15px 20px; - border-bottom: 1px solid @main_color_o; - } - - .sdc-general-tab-sub-title { - - .f-color.a; - .f-type._14_m; - padding: 15px 20px 15px 20px; - - } - - //scrollbar - .general-tab-scrollbar-container { - - .perfect-scrollbar; - width: 100%; - } - - //plus minus expand collapse - .general-tab-expand-collapse { - - &.expanded { - .expand-collapse-title { - .expand-collapse-title-icon { - .expand-collapse-minus-icon; - } - } - } - - .expand-collapse-title { - - padding: 8px 20px 4px 20px; - cursor: pointer; - &:hover { - background-color: @main_color_o; - } - - .expand-collapse-title-icon { - .hand; - .sprite-new; - .expand-collapse-plus-icon; - } - .expand-collapse-title-text { - max-width: 225px; - display: inline-block; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - padding-left: 10px; - line-height: 15px; - } - } - .selected { - background-color: @main_color_a; - .f-color.p; - } - - } - - .expand-collapse-sub-title { - max-width: 190px; - display: inline-block; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - padding: 10px 0 0 43px; - - } - - //resizable view - .resizable-container { - - flex: 1 1 auto; - display: flex; - flex-direction: column; - height: 90%; - - .resizable-section { - min-height: 50px; - flex: 1; - display: flex; - flex-flow: column; - &.resizable { - flex: 0 0 300px; - } - } - - //this is the resizable icon custom design for the angular resizable directive - .rg-top { - span { - margin-top: -5px; - &:before { - border-top: 1px dotted @main_color_m; - content: ''; - display: inline-block; - width: 39px; - height: 6px; - } - - border-top: 1px dotted @main_color_m; - border-bottom: 1px dotted @main_color_m; - width: 39px; - height: 4px; - } - } - } -} diff --git a/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view-model.ts b/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view-model.ts deleted file mode 100644 index f752e3dba7..0000000000 --- a/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view-model.ts +++ /dev/null @@ -1,134 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {ModalsHandler} from "app/utils"; -import {PropertyModel, DisplayModule, Component, ComponentInstance, Tab, Module} from "app/models"; -import {ExpandCollapseListData} from "app/directives/utils/expand-collapse-list-header/expand-collapse-list-header"; - -interface IComponentInstancesMap { - [key:string]: ComponentInstance -} - -export interface IHierarchyScope extends ng.IScope { - component:Component; - selectedIndex:number; - selectedModule:DisplayModule; - singleTab:Tab; - isLoading:boolean; - expandCollapseArtifactsList:ExpandCollapseListData; - expandCollapsePropertiesList:ExpandCollapseListData; - selectedInstanceId:string; - componentInstancesMap:IComponentInstancesMap; - - onModuleSelected(module:Module, selectedIndex:number, componentInstanceId?:string):void; - onModuleNameChanged(module:DisplayModule):void; - updateHeatName():void; - loadInstanceModules(instance:ComponentInstance):ng.IPromise; - openEditPropertyModal(property:PropertyModel, filteredProperties:Array):void; -} - -export class HierarchyViewModel { - - static '$inject' = [ - '$scope', - '$q', - 'ModalsHandler' - ]; - - constructor(private $scope:IHierarchyScope, private $q:ng.IQService, private ModalsHandler:ModalsHandler) { - this.$scope.component = this.$scope.singleTab.data; - this.$scope.isLoading = false; - this.$scope.expandCollapseArtifactsList = new ExpandCollapseListData(); - this.$scope.expandCollapsePropertiesList = new ExpandCollapseListData(); - this.$scope.componentInstancesMap = {}; - this.initScopeMethods(); - } - - private initScopeMethods():void { - - let collapseModuleData = ():void => { - this.$scope.expandCollapseArtifactsList.expandCollapse = false; - this.$scope.expandCollapsePropertiesList.expandCollapse = false; - this.$scope.expandCollapseArtifactsList.orderByField = "artifactName"; - this.$scope.expandCollapsePropertiesList.orderByField = "name"; - }; - - this.$scope.onModuleSelected = (module:Module, selectedIndex:number, componentInstanceId?:string):void => { - - let onSuccess = (module:DisplayModule) => { - console.log("Module Loaded: ", module); - this.$scope.selectedModule = module; - this.$scope.isLoading = false; - collapseModuleData(); - }; - - let onFailed = () => { - this.$scope.isLoading = false; - }; - - this.$scope.selectedIndex = selectedIndex; - if (!this.$scope.selectedModule || (this.$scope.selectedModule && this.$scope.selectedModule.uniqueId != module.uniqueId)) { - this.$scope.isLoading = true; - if (this.$scope.component.isService()) { - this.$scope.selectedInstanceId = componentInstanceId; - this.$scope.component.getModuleInstanceForDisplay(componentInstanceId, module.uniqueId).then(onSuccess, onFailed); - } else { - this.$scope.component.getModuleForDisplay(module.uniqueId).then(onSuccess, onFailed); - } - } - - const componentInstances: Array = this.$scope.component.componentInstances || []; - (_.values(module.members)).forEach((memberId) => { - if (!(memberId in this.$scope.componentInstancesMap)) { - const compInstance = componentInstances.find((c) => c.uniqueId === memberId); - if (compInstance) { - this.$scope.componentInstancesMap[compInstance.uniqueId] = compInstance; - } - } - }); - }; - - this.$scope.updateHeatName = () => { - this.$scope.isLoading = true; - - let originalName:string = this.$scope.selectedModule.name; - - let onSuccess = (module:Module) => { - console.log("Module name updated:", module.name); - this.$scope.selectedModule.name = module.name; - this.$scope.isLoading = false; - }; - - let onFailed = () => { - this.$scope.isLoading = false; - this.$scope.selectedModule.name = originalName; - }; - - this.$scope.selectedModule.updateName(); - this.$scope.component.updateGroupMetadata(new DisplayModule(this.$scope.selectedModule)).then(onSuccess, onFailed); - }; - - this.$scope.openEditPropertyModal = (property:PropertyModel, filteredProperties:Array):void => { - this.ModalsHandler.openEditModulePropertyModal(property, this.$scope.component, this.$scope.selectedModule, filteredProperties).then(() => { - }); - } - } -} diff --git a/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view.html b/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view.html deleted file mode 100644 index 423cbcd1f0..0000000000 --- a/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view.html +++ /dev/null @@ -1,123 +0,0 @@ - - -
    - -
    - -
    -
    - - -
    {{component.name}}
    - -
    -
    - - -
    -
    - -
    -
    -
    {{componentInstancesMap[memberId].name}}
    -
    -
    -
    -
    -
    - - -
    -
    - - -
    -
    - -
    - -
    -
    - - -
    -
    - -
    -
    -
    {{componentInstancesMap[memberId].name}}
    -
    -
    -
    -
    -
    - -
    - -
    -
    -
    {{selectedModule.name}}
    -
    - -
    -
    -
    Module ID:
    {{selectedModule.groupUUID}}
    -
    Customization ID:
    {{selectedModule.customizationUUID}}
    -
    Invariant UUID:{{selectedModule.invariantUUID}}
    -
    Version: {{selectedModule.version}}
    -
    IsBase: {{selectedModule.isBase}}
    - -
    - -
    -
    -
    - {{property.name}} -
    -
    Type: {{property.type}}
    -
    Value: {{property.value}}
    -
    -
    - -
    -
    -
    {{artifact.artifactName}}
    -
    UUID: {{artifact.artifactUUID}}
    -
    Version: {{artifact.artifactVersion}}
    -
    -
    -
    -
    -
    -
    diff --git a/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy.less b/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy.less deleted file mode 100644 index dee0eeb38b..0000000000 --- a/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy.less +++ /dev/null @@ -1,101 +0,0 @@ -.hierarchy-tab{ - width: 100%; - .hierarchy-module-list-container{ - padding: 0px 20px 0px 20px; - } - .module-data-container{ - - width: 100%; - height: 100%; - background-color: #e6f6fb; - border: 1px solid #009fdb; - border-top: 4px solid #009fdb; - box-shadow: 0.3px 1px 2px rgba(24, 24, 25, 0.32); - - .module-data { - - .selectable; - .module-name { - .f-type._14_m; - width: 87%; - } - .f-type._14_r; - .f-color.a; - padding: 10px 0px 10px 0px; - margin: 0px 20px 0px 20px; - //border-bottom: 1px solid rgba(0, 159, 219, 0.6); - - .small-font{ - font-size: 12px; - } - } - - .list-item{ - padding: 10px 0px 10px 0px; - margin: 0px 20px 0px 20px; - &:not(.last){ - border-bottom: 1px solid rgba(0, 159, 219, 0.6); - } - } - - .artifact-data{ - .selectable; - .f-type._12_r; - .f-color.m; - .artifact-name { - .f-type._14_r; - font-weight: bold; - } - } - - .property-data{ - .property-name{ - width: 100%; - .f-type._14_m; - font-weight: 400; - color: @main_color_a; - } - .property-info{ - color: @func_color_s; - .f-type._14_r; - width: 100%; - } - } - - .module-text-overflow { - max-width: 240px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - //display: inline-block; - } - } - - .hierarchy-modules-list{ - .expand-collapse-title{ - .expand-collapse-title-text{ - max-width: 202px; - } - } - } - - .hierarchy-module-member-list { - overflow: hidden; - background-color: @main_color_p; - } - - .edit-name-container { - float: right; - border-left: 1px solid #5cc1e7; - height: 20px; - width: 12%; - - .sdc-edit-icon { - float: right; - cursor: pointer; - position: relative; - top: 4px; - right: 5px; - } - } -} diff --git a/catalog-ui/src/app/view-models/tutorial-end/tutorial-end.html b/catalog-ui/src/app/view-models/tutorial-end/tutorial-end.html deleted file mode 100644 index 3dffbb9a79..0000000000 --- a/catalog-ui/src/app/view-models/tutorial-end/tutorial-end.html +++ /dev/null @@ -1,26 +0,0 @@ - - -
    - -

    -

    -
    - - -
    -
    -
    diff --git a/catalog-ui/src/app/view-models/tutorial-end/tutorial-end.less b/catalog-ui/src/app/view-models/tutorial-end/tutorial-end.less deleted file mode 100644 index 30fa4f7e8b..0000000000 --- a/catalog-ui/src/app/view-models/tutorial-end/tutorial-end.less +++ /dev/null @@ -1,41 +0,0 @@ -.sdc-tutorial-end-page { - - .bg_s; - width: 100%; - height: 100%; - position: absolute; - top: 0; - left: 0; - z-index: 999; - .opacity(0.8); - display: flex; - align-items: center; - - background-image: url('/assets/styles/images/welcome.png'); - background-repeat: no-repeat; - background-position: bottom left; - - .sdc-tutorial-end-page-main { - width: 600px; - height: 400px; - margin: 100px auto 100px auto; - padding: 80px; - } - - h2 { - .t_15; - margin: 0; - } - - .sdc-tutorial-end-page-description1 { - .c_2; - .opacity(0.8); - margin-top: 10px; - line-height: 22px; - } - - .w-sdc-btn-blue { - margin: 40px 10px 0 0; - } - -} diff --git a/catalog-ui/src/app/view-models/tutorial-end/tutorial-end.ts b/catalog-ui/src/app/view-models/tutorial-end/tutorial-end.ts deleted file mode 100644 index 5c4c4999e8..0000000000 --- a/catalog-ui/src/app/view-models/tutorial-end/tutorial-end.ts +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; - -interface ITutorialEndViewModelScope extends ng.IScope { -} - -export class TutorialEndViewModel { - - static '$inject' = [ - '$scope' - ]; - - constructor(private $scope:ITutorialEndViewModelScope) { - this.init(); - } - - private init = ():void => { - - } - -} diff --git a/catalog-ui/src/app/view-models/welcome/welcome-view.html b/catalog-ui/src/app/view-models/welcome/welcome-view.html deleted file mode 100644 index c342741f22..0000000000 --- a/catalog-ui/src/app/view-models/welcome/welcome-view.html +++ /dev/null @@ -1,25 +0,0 @@ - - -
    -
    -
    -
    -
    -

    Welcome to SDC

    -
    -
    -
    diff --git a/catalog-ui/src/app/view-models/welcome/welcome-view.ts b/catalog-ui/src/app/view-models/welcome/welcome-view.ts deleted file mode 100644 index 5ed7159d79..0000000000 --- a/catalog-ui/src/app/view-models/welcome/welcome-view.ts +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; - -export interface IWelcomeViewMode { - onCloseButtonClick():void; -} - -export class WelcomeViewModel { - - firstLoad:boolean = true; - alreadyAnimated:Array = []; - - static '$inject' = [ - '$scope', - '$state' - ]; - - constructor(private $scope:IWelcomeViewMode, - private $state:ng.ui.IStateService - ) { - this.init(); - this.initScope(); - window.setTimeout(():void => { - this.loadImages(():void=> { - window.setTimeout(():void =>{ - $(".sdc-welcome-new-page").addClass("animated fadeIn"); - },1000); - }); - },0); - } - - private initScope = ():void => { - let timeout = window.setTimeout(():void => { - this.$state.go("dashboard", {}); - }, 4000); - this.$scope.onCloseButtonClick = ():void => { - window.clearTimeout(timeout); - this.$state.go("dashboard", {}); - } - }; - - private init = ():void => { - let viewModelsHtmlBasePath:string = 'src/app/view-models/'; - $('body').keyup((e):void=> { - if (e.keyCode == 27) { // escape key maps to keycode `27` - this.$state.go('dashboard'); - } - }); - }; - - private loadImages = (callback:Function):void => { - let src = $('.sdc-welcome-wrapper').css('background-image'); - let url = src.match(/\((.*?)\)/)[1].replace(/('|")/g,''); - - let img = new Image(); - img.onload = function() { - callback(); - }; - img.src = url; - }; - -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.html b/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.html deleted file mode 100644 index c5ab3cc110..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.html +++ /dev/null @@ -1,101 +0,0 @@ - - -
    - -
    - -
    - -
    -
    - - -
    -
    {{header.title}} - -
    -
    - - -
    - - - -
    - There are no logs to display -
    - - -
    - - -
    - {{item.dateFormat}} -
    - - -
    - {{item.ACTION}} -
    - - -
    - {{item.COMMENT}} -
    - - -
    - {{item.MODIFIER}} -
    - - -
    - {{item.STATUS}} - -
    - -
    - -
    -
    -
    -
    - -
    - - - - diff --git a/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.less b/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.less deleted file mode 100644 index 24f83ec503..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.less +++ /dev/null @@ -1,80 +0,0 @@ -.activity-log { - .title-wrapper { - display: flex; - justify-content: flex-end; - } - - .table-container-flex .table .body .scrollbar-container { - max-height: 448px; - } - - .view-mode { - background-color: @main_color_p; - } - - .table{ - height: 490px; - margin-bottom: 0; - } - - .table-container-flex { - margin-top: 10px; - - .flex-item:nth-child(1) { width: 200px; } - .flex-item:nth-child(2) { flex-grow: 20; } - .flex-item:nth-child(3) { flex-grow: 30; } - .flex-item:nth-child(4) { flex-grow: 20; } - .flex-item:nth-child(5) { width: 80px; } - - .success { - position: absolute; - top: 11px; - right: 20px; - .sprite-new; - .sdc-success; - } - - .error { - position: absolute; - top: 11px; - right: 20px; - .sprite-new; - .sdc-error; - } - - } - - .data-row { - position: relative; - } - - .top-search { - float: right; - position: relative; - - input.search-text { - .border-radius(2px); - width: 245px; - height: 32px; - line-height: 32px; - border: 1px solid @main_color_o; - margin: 0; - outline: none; - text-indent: 10px; - - &::-webkit-input-placeholder { font-style: italic; } /* Safari, Chrome and Opera */ - &:-moz-placeholder { font-style: italic; } /* Firefox 18- */ - &::-moz-placeholder { font-style: italic; } /* Firefox 19+ */ - &:-ms-input-placeholder { font-style: italic; } /* IE 10+ */ - &:-ms-input-placeholder { font-style: italic; } /* Edge */ - } - - .magnification { - position: absolute; - top: 10px; - right: 10px; - } - - } - -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.ts b/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.ts deleted file mode 100644 index 452224a829..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.ts +++ /dev/null @@ -1,123 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import * as _ from "lodash"; -import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model"; -import {Activity} from "app/models"; -import {ActivityLogService} from "app/services"; - -export interface IActivityLogViewModelScope extends IWorkspaceViewModelScope { - activityDateArray:Array; //this is in order to sort the dates - activityLog:Array; - preVersion:string; - - tableHeadersList:Array; - reverse:boolean; - sortBy:string; - searchBind:string; - - getActivityLog(uniqueId:string):void; - onVersionChanged(version:any):void; - parseAction(action:string):string; - sort(sortBy:string):void; -} - -export class ActivityLogViewModel { - - static '$inject' = [ - '$scope', - '$state', - 'Sdc.Services.ActivityLogService' - ]; - - constructor(private $scope:IActivityLogViewModelScope, - private $state:ng.ui.IStateService, - private activityLogService:ActivityLogService) { - - this.initScope(); - this.$scope.setValidState(true); - this.initSortedTableScope(); - - // Set default sorting - this.$scope.sortBy = 'logDate'; - } - - private initScope():void { - - this.$scope.preVersion = this.$scope.component.version; - - this.$scope.onVersionChanged = (version:any):void => { - if (version.versionNumber != this.$scope.component.version) { - this.$scope.isLoading = true; - this.$scope.getActivityLog(version.versionId); - } - }; - - this.$scope.getActivityLog = (uniqueId:any):void => { - - let onError = (response) => { - this.$scope.isLoading = false; - console.info('onFaild', response); - - }; - - let onSuccess = (response:Array) => { - this.$scope.activityLog = _.sortBy(response, function (o) { - return o.TIMESTAMP; - }); //response; // - this.$scope.isLoading = false; - }; - - this.$scope.isLoading = true; - if (this.$scope.component.isResource()) { - this.activityLogService.getActivityLogService('resources', uniqueId).then(onSuccess, onError); - } - if (this.$scope.component.isService()) { - this.activityLogService.getActivityLogService('services', uniqueId).then(onSuccess, onError); - } - - }; - - if (!this.$scope.activityLog || this.$scope.preVersion != this.$scope.component.version) { - this.$scope.getActivityLog(this.$scope.component.uniqueId); - } - - this.$scope.parseAction = (action:string) => { - return action ? action.split(/(?=[A-Z])/).join(' ') : ''; - }; - - } - - private initSortedTableScope = ():void => { - this.$scope.tableHeadersList = [ - {title: 'Date', property: 'dateFormat'}, - {title: 'Action', property: 'ACTION'}, - {title: 'Comment', property: 'COMMENT'}, - {title: 'Username', property: 'MODIFIER'}, - {title: 'Status', property: 'STATUS'} - ]; - - this.$scope.sort = (sortBy:string):void => { - this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false; - this.$scope.sortBy = sortBy; - }; - }; -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view-model.ts deleted file mode 100644 index 312a663e8f..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view-model.ts +++ /dev/null @@ -1,99 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model"; -import {Component, AttributeModel} from "app/models"; -import {ModalsHandler} from "app/utils"; -import {ComponentServiceNg2} from "../../../../ng2/services/component-services/component.service"; -import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response"; - -interface IAttributesViewModelScope extends IWorkspaceViewModelScope { - tableHeadersList:Array; - reverse:boolean; - sortBy:string; - - addOrUpdateAttribute(attribute?:AttributeModel):void; - delete(attribute:AttributeModel):void; - sort(sortBy:string):void; -} - -export class AttributesViewModel { - - static '$inject' = [ - '$scope', - '$filter', - '$uibModal', - 'ModalsHandler', - 'ComponentServiceNg2' - ]; - - - constructor(private $scope:IAttributesViewModelScope, - private $filter:ng.IFilterService, - private $uibModal:ng.ui.bootstrap.IModalService, - private ModalsHandler:ModalsHandler, - private ComponentServiceNg2: ComponentServiceNg2) { - - this.initComponentAttributes(); - } - - private initComponentAttributes = () => { - if(this.$scope.component.attributes) { - this.initScope(); - } else { - this.ComponentServiceNg2.getComponentAttributes(this.$scope.component).subscribe((response:ComponentGenericResponse) => { - this.$scope.component.attributes = response.attributes; - this.initScope(); - }); - } - } - - - private initScope = ():void => { - - this.$scope.sortBy = 'name'; - this.$scope.reverse = false; - this.$scope.setValidState(true); - this.$scope.tableHeadersList = [ - {title: 'Name', property: 'name'}, - {title: 'Type', property: 'type'}, - {title: 'Default Value', property: 'defaultValue'} - ]; - this.$scope.sort = (sortBy:string):void => { - this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false; - this.$scope.sortBy = sortBy; - }; - - this.$scope.addOrUpdateAttribute = (attribute?:AttributeModel):void => { - this.ModalsHandler.openEditAttributeModal(attribute ? attribute : new AttributeModel(), this.$scope.component); - }; - - this.$scope.delete = (attribute:AttributeModel):void => { - - let onOk = ():void => { - this.$scope.component.deleteAttribute(attribute.uniqueId); - }; - let title:string = this.$filter('translate')("ATTRIBUTE_VIEW_DELETE_MODAL_TITLE"); - let message:string = this.$filter('translate')("ATTRIBUTE_VIEW_DELETE_MODAL_TEXT", "{'name': '" + attribute.name + "'}"); - this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk); - }; - } -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view.html b/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view.html deleted file mode 100644 index 675ae0c5c6..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view.html +++ /dev/null @@ -1,68 +0,0 @@ - - -
    -
    Add
    -
    -
    -
    -
    {{header.title}} - -
    -
    - -
    - -
    - -
    - There are no attributes to display
    - click here to add one - -
    -
    - -
    - - {{attribute.name}} - -
    - -
    - -
    - -
    - -
    - - -
    -
    -
    -
    -
    -
    - -
    -
    - -
    diff --git a/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes.less b/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes.less deleted file mode 100644 index 932daa167d..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes.less +++ /dev/null @@ -1,54 +0,0 @@ -.workspace-attributes { - - width: 93%; - display: inline-block; - .w-sdc-classic-btn { - float: right; - margin-bottom: 10px; - } - - .table{ - height:490px; - margin-bottom: 0; - } - - .table-container-flex { - margin-top: 0; - - .text{ - overflow: hidden; - text-overflow: ellipsis; - display: inline-block; - white-space: nowrap; - } - - .flex-item:nth-child(1) { - flex-grow: 15; - - .hand; - span.table-arrow { - margin-right: 7px; - } - } - - .flex-item:nth-child(2) { - flex-grow: 6; - } - - .flex-item:nth-child(3) { - flex-grow: 9; - } - - .flex-item:nth-child(4) { - flex-grow: 3; - padding-top: 10px; - } - - .flex-item:nth-child(5) { - flex-grow: 1; - - } - - } - -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view-model.ts deleted file mode 100644 index 2270a7b06e..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view-model.ts +++ /dev/null @@ -1,501 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -'use strict'; -import * as _ from "lodash"; -import { Component, ComponentInstance, IAppMenu, Requirement, Capability, ButtonModel } from "app/models"; -import { SharingService, CacheService, EventListenerService, LeftPaletteLoaderService } from "app/services"; -import { ModalsHandler, GRAPH_EVENTS, ComponentFactory, ChangeLifecycleStateHandler, MenuHandler, EVENTS, ComponentInstanceFactory } from "app/utils"; -import { IWorkspaceViewModelScope } from "../../workspace-view-model"; -import { ComponentGenericResponse } from "app/ng2/services/responses/component-generic-response"; -import { Resource } from "app/models/components/resource"; -import { ResourceType, ComponentType } from "app/utils/constants"; -import { ComponentServiceFactoryNg2 } from "app/ng2/services/component-services/component.service.factory"; -import { ServiceGenericResponse } from "app/ng2/services/responses/service-generic-response"; -import { Service } from "app/models/components/service"; -import { ZoneInstance } from "app/models/graph/zones/zone-instance"; -import { ComponentServiceNg2 } from "app/ng2/services/component-services/component.service"; -import { ModalService as ModalServiceSdcUI} from "sdc-ui/lib/angular/modals/modal.service" -import { IModalConfig, IModalButtonComponent } from "sdc-ui/lib/angular/modals/models/modal-config"; -import { ValueEditComponent } from "app/ng2/components/ui/forms/value-edit/value-edit.component"; -import { UnsavedChangesComponent } from "../../../../ng2/components/ui/forms/unsaved-changes/unsaved-changes.component"; -import { ModalButtonComponent } from "sdc-ui/lib/angular/components"; - - - -export interface ICompositionViewModelScope extends IWorkspaceViewModelScope { - - currentComponent:Component; - - //Added for now, in the future need to remove and use only id and type to pass to tabs. - selectedComponent: Component; - selectedZoneInstance: ZoneInstance; - - componentInstanceNames: Array; - isLoading:boolean; - graphApi:any; - sharingService:SharingService; - sdcMenu:IAppMenu; - version:string; - isViewOnly:boolean; - isCanvasTagging:boolean; - isLoadingRightPanel:boolean; - disabledTabs:boolean; - openVersionChangeModal(pathsToDelete:string[]):ng.IPromise; - onComponentInstanceVersionChange(component:Component); - isComponentInstanceSelected():boolean; - updateSelectedComponent():void; - openUpdateModal(); - deleteSelectedComponentInstance():void; - onBackgroundClick():void; - setSelectedInstance(componentInstance:ComponentInstance):void; - setSelectedZoneInstance(zoneInstance: ZoneInstance):void; - changeZoneInstanceName(newName:string):void; - printScreen():void; - isPNF():boolean; - isConfiguration():boolean; - preventMoveTab(state: boolean):void; - registerCreateInstanceEvent(callback: Function):void; - unregisterCreateInstanceEvent():void; - registerChangeComponentInstanceNameEvent(callback: Function):void; - unregisterChangeComponentInstanceNameEvent():void; - - ComponentServiceNg2:ComponentServiceNg2, - cacheComponentsInstancesFullData:Component; -} - -export class CompositionViewModel { - - static '$inject' = [ - '$scope', - '$log', - 'sdcMenu', - 'MenuHandler', - '$uibModal', - '$state', - 'Sdc.Services.SharingService', - '$filter', - 'Sdc.Services.CacheService', - 'ComponentFactory', - 'ChangeLifecycleStateHandler', - 'LeftPaletteLoaderService', - 'ModalsHandler', - 'ModalServiceSdcUI', - 'EventListenerService', - 'ComponentServiceFactoryNg2', - 'ComponentServiceNg2', - 'Notification' - ]; - - constructor(private $scope:ICompositionViewModelScope, - private $log:ng.ILogService, - private sdcMenu:IAppMenu, - private MenuHandler:MenuHandler, - private $uibModal:ng.ui.bootstrap.IModalService, - private $state:ng.ui.IStateService, - private sharingService:SharingService, - private $filter:ng.IFilterService, - private cacheService:CacheService, - private ComponentFactory:ComponentFactory, - private ChangeLifecycleStateHandler:ChangeLifecycleStateHandler, - private LeftPaletteLoaderService:LeftPaletteLoaderService, - private ModalsHandler:ModalsHandler, - private ModalServiceSdcUI: ModalServiceSdcUI, - private eventListenerService:EventListenerService, - private ComponentServiceFactoryNg2: ComponentServiceFactoryNg2, - private ComponentServiceNg2:ComponentServiceNg2, - private Notification:any - ) { - - this.$scope.setValidState(true); - this.initScope(); - this.initGraphData(); - this.registerGraphEvents(this.$scope); - } - - - private initGraphData = ():void => { - if(!this.hasCompositionGraphData(this.$scope.component)) { - this.$scope.isLoading = true; - let service = this.ComponentServiceFactoryNg2.getComponentService(this.$scope.component); - service.getComponentCompositionData(this.$scope.component).subscribe((response:ComponentGenericResponse) => { - if (this.$scope.component.isService()) { - ( this.$scope.component).forwardingPaths = (response).forwardingPaths; - } - this.$scope.component.componentInstances = response.componentInstances || []; - this.$scope.component.componentInstancesRelations = response.componentInstancesRelations || []; - this.$scope.component.policies = response.policies || []; - this.$scope.component.groupInstances = response.groupInstances || []; - this.$scope.isLoading = false; - this.initComponent(); - this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_COMPOSITION_GRAPH_DATA_LOADED); - }); - } else { - this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_COMPOSITION_GRAPH_DATA_LOADED); - } - this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_COMPOSITION_GRAPH_DATA_LOADED); - }; - - private hasCompositionGraphData = (component:Component):boolean => { - return !!(component.componentInstances && component.componentInstancesRelations && component.policies && component.groupInstances); - }; - - private cacheComponentsInstancesFullData:Array; - - private initComponent = ():void => { - this.$scope.currentComponent = this.$scope.component; - this.$scope.selectedComponent = this.$scope.currentComponent; - this.$scope.selectedZoneInstance = null; - this.updateUuidMap(); - this.$scope.isViewOnly = this.$scope.isViewMode(); - }; - - private registerGraphEvents = (scope:ICompositionViewModelScope):void => { - this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_NODE_SELECTED, scope.setSelectedInstance); - this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_ZONE_INSTANCE_SELECTED, scope.setSelectedZoneInstance); - this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_GRAPH_BACKGROUND_CLICKED, scope.onBackgroundClick); - this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_CANVAS_TAG_START, () => { - scope.isCanvasTagging = true; - this.eventListenerService.notifyObservers(EVENTS.ON_WORKSPACE_UNSAVED_CHANGES, true, this.showUnsavedChangesAlert); - }); - this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_CANVAS_TAG_END, () => { - scope.isCanvasTagging = false; - this.resetUnsavedChanges(); - }); - this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_ZONE_INSTANCE_NAME_CHANGED, scope.changeZoneInstanceName); - this.eventListenerService.registerObserverCallback(EVENTS.UPDATE_PANEL, this.removeSelectedZoneInstance); - }; - - private showUnsavedChangesAlert = (afterSave?:Function):Promise => { - let deferred = new Promise((resolve, reject)=> { - const modal = this.ModalServiceSdcUI.openCustomModal( - { - title: "Unsaved Changes", - size: 'sm', - type: 'custom', - - buttons: [ - {id: 'cancelButton', text: 'Cancel', type: 'secondary', size: 'xsm', closeModal: true, callback: () => reject()}, - {id: 'discardButton', text: 'Discard', type: 'secondary', size: 'xsm', closeModal: true, callback: () => { this.resetUnsavedChanges(); resolve()}}, - {id: 'saveButton', text: 'Save', type: 'primary', size: 'xsm', closeModal: true, callback: () => { reject(); this.saveUnsavedChanges(afterSave); }} - ] as IModalButtonComponent[] - }, UnsavedChangesComponent, { isValidChangedData: true}); - }); - - return deferred; - } - - private unRegisterGraphEvents = (scope: ICompositionViewModelScope):void => { - this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_NODE_SELECTED, scope.setSelectedInstance); - this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_ZONE_INSTANCE_SELECTED, scope.setSelectedZoneInstance); - this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_GRAPH_BACKGROUND_CLICKED, scope.onBackgroundClick); - this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_CANVAS_TAG_START); - this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_CANVAS_TAG_END); - this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_ZONE_INSTANCE_NAME_CHANGED, scope.changeZoneInstanceName); - this.eventListenerService.unRegisterObserver(EVENTS.UPDATE_PANEL, this.removeSelectedZoneInstance); - - }; - - private resetUnsavedChanges = () => { - this.eventListenerService.notifyObservers(EVENTS.ON_WORKSPACE_UNSAVED_CHANGES, false); - } - - private saveUnsavedChanges = (afterSaveFunction?:Function):void => { - this.$scope.selectedZoneInstance.forceSave.next(afterSaveFunction); - this.eventListenerService.notifyObservers(EVENTS.ON_WORKSPACE_UNSAVED_CHANGES, false); - } - - private openUpdateComponentInstanceNameModal = ():void => { - - let modalConfig:IModalConfig = { - title: "Edit Name", - size: "sm", - type: "custom", - testId: "renameInstanceModal", - buttons: [ - {id: 'saveButton', text: 'OK', size: 'xsm', callback: this.saveInstanceName, closeModal: false}, - {id: 'cancelButton', text: 'Cancel', size: 'sm', closeModal: true} - ] - }; - - this.ModalServiceSdcUI.openCustomModal(modalConfig, ValueEditComponent, {name: this.$scope.currentComponent.selectedInstance.name, validityChangedCallback: this.enableOrDisableSaveButton}); - - }; - - - private enableOrDisableSaveButton = (shouldEnable: boolean): void => { - let saveButton: ModalButtonComponent = this.ModalServiceSdcUI.getCurrentInstance().getButtonById('saveButton'); - saveButton.disabled = !shouldEnable; - } - - private saveInstanceName = () => { - let currentModal = this.ModalServiceSdcUI.getCurrentInstance(); - let nameFromModal:string = currentModal.innerModalContent.instance.name; - - if(nameFromModal != this.$scope.currentComponent.selectedInstance.name){ - currentModal.buttons[0].disabled = true; - let componentInstanceModel:ComponentInstance = ComponentInstanceFactory.createComponentInstance(this.$scope.currentComponent.selectedInstance); - componentInstanceModel.name = nameFromModal; - - let onFailed = (error) => { - currentModal.buttons[0].disabled = false; - }; - let onSuccess = (componentInstance:ComponentInstance) => { - - this.$scope.currentComponent.selectedInstance.name = componentInstance.name; - //update requirements and capabilities owner name - _.forEach(this.$scope.currentComponent.selectedInstance.requirements, (requirementsArray:Array) => { - _.forEach(requirementsArray, (requirement:Requirement):void => { - requirement.ownerName = componentInstance.name; - }); - }); - - _.forEach(this.$scope.currentComponent.selectedInstance.capabilities, (capabilitiesArray:Array) => { - _.forEach(capabilitiesArray, (capability:Capability):void => { - capability.ownerName = componentInstance.name; - }); - }); - this.ModalServiceSdcUI.closeModal(); - this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_COMPONENT_INSTANCE_NAME_CHANGED, this.$scope.currentComponent.selectedInstance); - }; - - this.$scope.currentComponent.updateComponentInstance(componentInstanceModel).then(onSuccess, onFailed); - } else { - this.ModalServiceSdcUI.closeModal(); - } - - }; - - private removeSelectedComponentInstance = ():void => { - this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_DELETE_COMPONENT_INSTANCE, this.$scope.currentComponent.selectedInstance) - this.$scope.currentComponent.selectedInstance = null; - this.$scope.selectedComponent = this.$scope.currentComponent; - }; - - private removeSelectedZoneInstance = ():void => { - this.$scope.currentComponent.selectedInstance = null; - this.$scope.selectedZoneInstance = null; - this.$scope.selectedComponent = this.$scope.currentComponent; - } - - private updateUuidMap = ():void => { - /** - * In case user press F5, the page is refreshed and this.sharingService.currentEntity will be undefined, - * but after loadService or loadResource this.sharingService.currentEntity will be defined. - * Need to update the uuidMap with the new resource or service. - */ - this.sharingService.addUuidValue(this.$scope.currentComponent.uniqueId, this.$scope.currentComponent.uuid); - }; - - private initScope = ():void => { - this.$scope.sharingService = this.sharingService; - this.$scope.sdcMenu = this.sdcMenu; - this.$scope.isLoading = false; - this.$scope.isLoadingRightPanel = false; - this.$scope.isCanvasTagging = false; - this.$scope.graphApi = {}; - this.$scope.version = this.cacheService.get('version'); - this.initComponent(); - - this.cacheComponentsInstancesFullData = new Array(); - - this.$scope.isComponentInstanceSelected = ():boolean => { - return this.$scope.currentComponent && this.$scope.currentComponent.selectedInstance != undefined && this.$scope.currentComponent.selectedInstance != null; - }; - - this.$scope.$on('$destroy', () => { - this.unRegisterGraphEvents(this.$scope); - }) - - this.$scope.restoreComponent = ():void => { - this.ComponentServiceNg2.restoreComponent(this.$scope.selectedComponent.componentType, this.$scope.selectedComponent.uniqueId).subscribe(() => { - this.Notification.success({ - message: '<' + this.$scope.component.name + '> ' + this.$filter('translate')("ARCHIVE_SUCCESS_MESSAGE_TEXT"), - title: this.$filter('translate')("ARCHIVE_SUCCESS_MESSAGE_TITLE") - }); - this.$scope.selectedComponent.archived = false; - } - ) - }; - - this.$scope.updateSelectedComponent = ():void => { - if (this.$scope.currentComponent.selectedInstance) { - let parentComponentUid = this.$scope.currentComponent.selectedInstance.componentUid - if(this.$scope.currentComponent.selectedInstance.originType === ComponentType.SERVICE_PROXY){ - parentComponentUid = this.$scope.currentComponent.selectedInstance.sourceModelUid; - } - let componentParent = _.find(this.cacheComponentsInstancesFullData, (component) => { - return component.uniqueId === parentComponentUid; - }); - if (componentParent) { - this.$scope.selectedComponent = componentParent; - } - else { - try { - let onSuccess = (component:Component) => { - this.$scope.isLoadingRightPanel = false; - this.$scope.selectedComponent = component; - this.cacheComponentsInstancesFullData.push(component); - }; - let onError = (component:Component) => { - console.log("Error updating selected component"); - this.$scope.isLoadingRightPanel = false; - }; - this.ComponentFactory.getComponentFromServer(this.$scope.currentComponent.selectedInstance.originType, parentComponentUid).then(onSuccess, onError); - } catch (e) { - console.log("Error updating selected component", e); - this.$scope.isLoadingRightPanel = false; - } - } - } - else { - - this.$scope.selectedComponent = this.$scope.currentComponent; - } - }; - - this.$scope.setSelectedInstance = (selectedComponent:ComponentInstance):void => { - - this.$log.debug('composition-view-model::onNodeSelected:: with id: ' + selectedComponent.uniqueId); - this.$scope.currentComponent.setSelectedInstance(selectedComponent); - this.$scope.selectedZoneInstance = null; - this.$scope.updateSelectedComponent(); - - if (this.$state.current.name === 'workspace.composition.api') { - this.$state.go('workspace.composition.details'); - } - if(!selectedComponent.isServiceProxy() && (this.$state.current.name === 'workspace.composition.consumption' || this.$state.current.name === 'workspace.composition.dependencies')) { - this.$state.go('workspace.composition.details'); - } - }; - - this.$scope.setSelectedZoneInstance = (zoneInstance: ZoneInstance): void => { - this.$scope.currentComponent.selectedInstance = null; - this.$scope.selectedZoneInstance = zoneInstance; - }; - - this.$scope.onBackgroundClick = ():void => { - this.$scope.currentComponent.selectedInstance = null; - this.$scope.selectedZoneInstance = null; - this.$scope.selectedComponent = this.$scope.currentComponent; - - if (this.$state.current.name === 'workspace.composition.api' || this.$state.current.name === 'workspace.composition.consumption' || this.$state.current.name === 'workspace.composition.dependencies') { - this.$state.go('workspace.composition.details'); - } - - if(this.$scope.selectedComponent.isService() && this.$state.current.name === 'workspace.composition.relations'){ - this.$state.go('workspace.composition.api'); - } - }; - - this.$scope.openUpdateModal = ():void => { - this.openUpdateComponentInstanceNameModal(); - }; - - this.$scope.changeZoneInstanceName = (newName:string):void => { - this.$scope.selectedZoneInstance.instanceData.name = newName; - }; - - this.$scope.deleteSelectedComponentInstance = ():void => { - const {currentComponent} = this.$scope; - const {title, message} = this.$scope.sdcMenu.alertMessages['deleteInstance']; - let modalText = message.format([currentComponent.selectedInstance.name]); - - if (currentComponent.isService()) { - const {forwardingPaths} = (currentComponent); - const instanceId = currentComponent.selectedInstance.uniqueId; - - const relatedPaths = _.filter(forwardingPaths, forwardingPath => { - const pathElements = forwardingPath.pathElements.listToscaDataDefinition; - return pathElements.find(path => path.fromNode === instanceId || path.toNode === instanceId); - }); - - if (relatedPaths.length) { - const pathNames = _.map(relatedPaths, path => path.name).join(', '); - modalText += `

    The following service paths will be erased: ${pathNames}

    `; - } - } - this.ModalServiceSdcUI.openAlertModal(title, modalText, "OK", this.removeSelectedComponentInstance, "deleteInstanceModal"); - }; - - this.$scope.openVersionChangeModal = (pathsToDelete:string[]):ng.IPromise => { - const {currentComponent} = this.$scope; - const {forwardingPaths} = currentComponent; - - const relatedPaths = _.filter(forwardingPaths, path => - _.find(pathsToDelete, id => - path.uniqueId === id - ) - ).map(path => path.name); - const pathNames = _.join(relatedPaths, ', ') || 'none'; - - const {title, message} = this.$scope.sdcMenu.alertMessages['upgradeInstance']; - return this.ModalsHandler.openConfirmationModal(title, message.format([pathNames]), false); - }; - - this.$scope.onComponentInstanceVersionChange = (component:Component):void => { - let onChange = () => { - this.$scope.currentComponent = component; - this.$scope.setComponent(this.$scope.currentComponent); - this.$scope.updateSelectedComponent(); - this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_VERSION_CHANGED, this.$scope.currentComponent); - }; - - if (component.isService()) { - const service = this.ComponentServiceFactoryNg2.getComponentService(component); - service.getComponentCompositionData(component).subscribe((response:ServiceGenericResponse) => { - (component).forwardingPaths = response.forwardingPaths; - onChange(); - }); - } else { - onChange(); - } - }; - - this.$scope.isPNF = (): boolean => { - return this.$scope.selectedComponent.isResource() && (this.$scope.selectedComponent).resourceType === ResourceType.PNF; - }; - - this.$scope.isConfiguration = (): boolean => { - return this.$scope.selectedComponent.isResource() && (this.$scope.selectedComponent).resourceType === ResourceType.CONFIGURATION; - }; - - this.$scope.preventMoveTab = (state: boolean): void => { - this.$scope.disabledTabs = state; - }; - - this.eventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE, this.$scope.reload); - - this.$scope.registerCreateInstanceEvent = (callback: Function): void => { - this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_CREATE_COMPONENT_INSTANCE, callback); - }; - - this.$scope.unregisterCreateInstanceEvent = (): void => { - this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_CREATE_COMPONENT_INSTANCE); - }; - - this.$scope.registerChangeComponentInstanceNameEvent = (callback: Function): void => { - this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_COMPONENT_INSTANCE_NAME_CHANGED, callback); - }; - - this.$scope.unregisterChangeComponentInstanceNameEvent = (): void => { - this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_COMPONENT_INSTANCE_NAME_CHANGED); - }; - } -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view.html deleted file mode 100644 index c2d6007edc..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view.html +++ /dev/null @@ -1,159 +0,0 @@ - - -
    - -
    - - - - - -
    - -
    - -
    - -
    - -
    - -
    -
    -
    -
    -
    -
    - - -
    - -
    -
    - -
    - - - - - - - - - - - - - - -
    -
    - -
    - - - - -
    - - - -
    - - - -
    -
    diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/composition.less b/catalog-ui/src/app/view-models/workspace/tabs/composition/composition.less deleted file mode 100644 index f37a492572..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/composition.less +++ /dev/null @@ -1,955 +0,0 @@ - .i-sdc-designer-leftbar-section-popup-panel { - position: absolute; - display: inline-block; - background-color: white; - border: solid 1px #d2d2d2; - border-top: solid 3px #13a7df; - width: 140px; - height: 40px; - z-index: 10000; - } - - .i-sdc-designer-leftbar-section-popup-panel-group { - padding-left: 8px; - padding-top: 8px; - } - - .i-sdc-designer-leftbar-section-popup-panel-plus { - border-radius: 50%; - color: white; - background-color: #13a7df; - width: 20px; - text-align: center; - display: inline-block; - cursor: pointer; - } - - .i-sdc-designer-leftbar-section-popup-panel-title { - padding-left: 10px; - display: inline-block; - } - -.composition{ - .sdc-workspace-container{ - .w-sdc-main-container{ - .w-sdc-main-right-container{ - left:0; - //overflow-y: scroll; - .sdc-workspace-top-bar { - padding-left: 295px; - .not-latest{ - left: 270px; - } - } - .w-sdc-main-container-body-content{ - padding: 0 0 0 247px; - } - - > div:first-child{ - padding: 0; - } - } - } - } - - .custom-modal { - /* Hack solution to hide canvas tooltips under modals */ - z-index: 20000 !important; - } -} - -.workspace-composition { - height:100%; - display: block; - text-align: left; - align-items: left; - padding: 0; - - - - // --------------------------------------------------------------------------------------------------- - // Sidebar - // --------------------------------------------------------------------------------------------------- - - - - .w-sdc-designer-sidebar-toggle { - background-color: @main_color_p; - border-left: 1px solid @main_color_o; - border-bottom: 1px solid @main_color_o; - height: 21px; - position: absolute; - right: 0; - top: 53px; - width: 17px; - transition: right 0.2s; - z-index: 10; - .box-shadow(-1px 1px 3px 0 @main_color_n); - - &.active { - right: 302px; - .w-sdc-designer-sidebar-toggle-icon{ - transform: rotate(180deg); - } - } - - } - - .w-sdc-designer-sidebar-toggle-icon { - margin-left: 6px; - margin-top: 6px; - } - - .w-sdc-designer-sidebar { - background-color:@main_color_p ; - .noselect; - bottom: 0; - position: fixed; - right: -302px; - width: 302px; - top: 103px; - transition: right 0.2s; - z-index: 9; - .box-shadow(-7px -3px 6px -8px @main_color_n); - - } - - .w-sdc-designer-sidebar-toggle.active + .w-sdc-designer-sidebar { - right: 0; - - } - - .w-sdc-designer-sidebar-head { - padding: 36px 30px 30px 30px; - height: 120px; - } - - .w-sdc-designer-sidebar-logo-ph { - display: inline-block; - vertical-align: middle; - line-height: 60px; - height: 60px; - } - - .w-sdc-designer-sidebar-logo { - .g_6; - display: inline-block; - margin-left: 10px; - font-weight: 500; - } - - .w-sdc-designer-sidebar-logo-title { - .s_16_r; - .selectable; - vertical-align: middle; - text-overflow: ellipsis; - max-width: 167px; - display: inline-block; - white-space: nowrap; - overflow: hidden; - } - - .w-sdc-designer-update-resource-icon { - .hand; - position: absolute; - right: 20px; - top: 10px; - } - - .w-sdc-designer-delete-resource-icon { - .hand; - position: absolute; - right: 40px; - top: 10px; - } - - .w-sdc-designer-restore-button { - .hand; - position:absolute; - right: 20px; - top:10px; - width:65px; - } - .w-sdc-designer-sidebar-tabs { - .bg_c; - } - - .w-sdc-designer-sidebar-tabs::after { - clear: both; - content: ''; - display: table; - } - - .i-sdc-designer-sidebar-tab { - background-color: @main_color_p; - border: 1px solid @tlv_color_u;; - border-left: none; - display: inline-block; - float: left; - height: 36px; - padding-top: 9px; - text-align: center; - width: 60px; - .hand; - - &:focus { - outline: none; - } - &.tab-disabled { - /* .disabled; */ - } - &.active, &:hover:enabled { - background-color: @tlv_color_u; - .i-sdc-designer-sidebar-tab-icon { - opacity: 1; - - - } - - } - - div& { - padding-top: 0; - } - /*for tooltip on disabled buttons*/ - } - - .i-sdc-designer-sidebar-tab-icon { - margin-top: 5px ; - &.import-icon { - transform: rotate(270deg); - } - // opacity: .4; - } - - .w-sdc-designer-sidebar-tab-content { - .perfect-scrollbar; - height: 100%; - } - - .w-sdc-designer-sidebar-tab-content-view { - position: absolute; - top: 156px; - bottom: 0; - width: 100%; - padding-bottom: 10px; - - } - - .w-sdc-designer-sidebar-section { - } - - .w-sdc-designer-sidebar-section-title { - .m_14_m; - background-color: @tlv_color_u; - .hand; - clear: both; - height: 32px; - line-height: 32px; - margin-top: 1px; - padding: 0 10px 0 20px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - position: relative; - width: 100%; - display: block; - - &.expanded { - .w-sdc-designer-sidebar-section-title-icon { - transform: rotate(180deg); - } - } - } - - .w-sdc-designer-sidebar-section-title-text { - max-width: 240px; - display: inline-block; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - position: relative; - } - - .w-sdc-designer-sidebar-section-title-icon { - .hand; - .sprite-new; - .arrow-up; - right: 16px; - top: 13px; - transition: .3s all; - position: absolute; - } - - .w-sdc-designer-sidebar-section-content { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - } - - .w-sdc-designer-sidebar-section-title { - text-transform: uppercase; - } - - .w-sdc-designer-sidebar-section-title + .w-sdc-designer-sidebar-section-content { - margin: 0 auto; - } - - .w-sdc-designer-sidebar-section-title.expanded + .w-sdc-designer-sidebar-section-content { - margin: 0 auto 1px; - - } - - .i-sdc-designer-sidebar-section-content-item { - .b_7; - font-size: 13px; - margin-bottom: 5px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - //max-width: 250px; - - &.description { - margin-top: 28px; - white-space: normal; - word-wrap: break-word; - } - } - - .i-sdc-designer-sidebar-section-content-item-tag { - .g_7; - .bg_c; - border-radius: 4px; - //fix long name for firefox: - display: block; - float: left; - line-height: 25px; - margin: 0 4px 6px 0; - min-width: 50px; - padding: 0 9px; - text-align: center; - max-width: 280px; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - } - - .w-sdc-designer-sidebar-section-footer { - margin-top: 10px; - text-align: center; - width: 100%; - } - - - - .w-sdc-designer-sidebar-section-footer-action { - width: 180px; - margin-top: 10px; - } - - //////////////////////Relationship - .w-sdc-designer-sidebar-section-requirements { - border-bottom: 1px solid @color_e; - margin: 0 13px 20px 13px; - padding: 15px 0 0; - } - - .w-sdc-designer-sidebar-section-requirements-item { - margin-bottom: 20px; - } - - .w-sdc-designer-sidebar-section-requirements-label { - display: inline-block; - overflow: hidden; - text-overflow: ellipsis; - vertical-align: middle; - white-space: nowrap; - width: 102px; - } - - .w-sdc-designer-sidebar-section-requirements-select { - border: 1px solid @color_e; - min-height: 30px; - padding: 4px 13px; - width: 168px; - } - - //////////////////////Properties - .i-sdc-designer-sidebar-section-content-item-property-and-attribute { - .b_7; - border-bottom: 1px solid @color_e; - min-height: 72px; - padding: 15px 10px 10px 18px; - position: relative; - - &:first-child { - //margin-top: -18px; - } - - &:hover { - // .bg_c_hover; - .bg_c; - transition: all .3s; - - .i-sdc-designer-sidebar-section-content-item-button { - display: block; - } - } - } - - .i-sdc-designer-sidebar-section-content-item-property-and-attribute-label { - overflow: hidden; - text-overflow: ellipsis; - max-width: 200px; - white-space: nowrap; - display: inline-block; - &:hover { - .a_7; - } - } - - .i-sdc-designer-sidebar-section-content-item-property-value { - overflow: hidden; - text-overflow: ellipsis; - max-width: 200px; - display: inline-block; - white-space: nowrap; - - } - - .i-sdc-designer-sidebar-section-content-item-property-label-value { - } - - .i-sdc-designer-sidebar-section-content-item-button { - display: none; - position: absolute; - top: 25px; - - &.update { - background-color: transparent; - border: 0; - right: 60px; - } - - &.delete { - background-color: transparent; - border: 0; - right: 13px; - } - - &.download { - background-color: transparent; - border: 0; - right: 35px; - } - - &.download-env { - background-color: transparent; - border: 0; - right: 35px; - margin-top: 65px; - } - - &.update-env { - background-color: transparent; - border: 0; - right: 15px; - margin-top: 65px; - } - - &.attach { - background-color: transparent; - border: 0; - right: 15px; - } - } - - // --------------------------------------------------------------------------------------------------- - // Canvas - // --------------------------------------------------------------------------------------------------- - .w-sdc-designer-canvas { - height:100%; - .noselect; - .bg_c; - bottom: 0; - // position: fixed; - //right: 0; - //left: 240px; - //top: 94px; - .view-mode{ - background-color: #f8f8f8; - border:0; - } - } - - .w-sdc-designer-canvas.sidebaractive { - //right: 300px; - } - - .w-sdc-designer-element { - .hand; - width: 200px; - height: 100px; - position: absolute; - text-align: center; - top: 50%; - margin-top: -200px; - left: 50%; - margin-left: -50px; - } - - .w-sdc-designer-resource-label { - .q_7; - } - - .w-sdc-designer-resource-label-indicator { - .bg_q; - border-radius: 50%; - display: inline-block; - height: 10px; - margin-right: 6px; - vertical-align: middle; - width: 10px; - - &.valid { - .bg_l; - } - - &.invalid { - .bg_h; - } - } - - // --------------------------------------------------------------------------------------------------- - // Leftbar - // --------------------------------------------------------------------------------------------------- - .w-sdc-designer-leftbar { - background-color: @main_color_p; - bottom: 0; - left: 0; - overflow-y: scroll; - overflow-x: hidden; - position: absolute; - top: 0; - width: 244px; - .box-shadow(7px -3px 6px -8px @main_color_n); - - } - - .w-sdc-designer-leftbar-title { - - .p_16_m; - background-color: @main_color_n; - line-height: 40px; - padding: 0 17px; - } - - .w-sdc-designer-leftbar-title-count { - float: right; - } - - .w-scd-diagram-container { - // left: 240px; - //right: 300px; - } - - .w-sdc-designer-leftbar-search { - background-color: @tlv_color_u; - padding: 10px; - white-space: nowrap; - position: relative; - } - - .w-sdc-designer-leftbar-search-input { - border: 1px solid @color_e; - .border-radius(4px); - height: 30px; - margin: 0; - padding: 0px 28px 3px 10px; - vertical-align: 4px; - width: 100%; - outline: none; - font-style: italic; - } - - .w-sdc-designer-leftbar-search-filter { - - } - - .i-sdc-designer-leftbar-section { - .hand; - } - - .i-sdc-designer-leftbar-section-title { - .m_14_m; - background-color: @tlv_color_u; - .hand; - clear: both; - height: 40px; - line-height: 40px; - margin-top: 1px; - padding: 0 10px; - position: relative; - text-transform: uppercase; - font-weight: bold; - } - - .i-sdc-designer-leftbar-section-title-icon { - .hand; - .sprite-new; - .arrow-up; - width: 15px; - height: 9px; - position: absolute; - right: 13px; - top: 18px; - transition: .3s all; - } - - .i-sdc-designer-leftbar-section.expanded .i-sdc-designer-leftbar-section-title-icon { - transform: rotate(180deg); - margin-right: 2px; - } - - .i-sdc-designer-leftbar-section-content { - background-color: @main_color_o; - } - - .i-sdc-designer-leftbar-section-content-item { - background-color: @main_color_p; - overflow: hidden; - - &:hover { - background-color: @main_color_p; - } - - .cp{ - margin: 6px; - } - - .vl{ - margin: 6px; - } - } - - .i-sdc-designer-leftbar-section-content-subcat { - .m_14_m; - background-color: @tlv_color_t; - line-height: 35px; - padding: 0 10px; - cursor: default; - - - &:hover { - background-color: @func_color_r; - } - - - } - - .i-sdc-designer-leftbar-section .i-sdc-designer-leftbar-section-content .i-sdc-designer-leftbar-section-content-item { - max-height: 0px; - margin: 0 auto; - transition: all .3s; - } - - .i-sdc-designer-leftbar-section.expanded .i-sdc-designer-leftbar-section-content .i-sdc-designer-leftbar-section-content-item { - max-height: 64px; - margin: 0 auto 1px auto; - // padding: 4px 13px; - } - - .i-sdc-designer-leftbar-section.expanded .i-sdc-designer-leftbar-section-content .i-sdc-designer-leftbar-section-content-subcat { - margin: 0; - } - - .i-sdc-designer-leftbar-section-content-item-icon-ph { - display: inline-block; - margin: 12px 0 12px 10px; - pointer-events: auto; - height: 45px; - width: 40px; - float: left; - display: flex; - align-items: center; - .non-certified { - position: relative; - left: -4px; - top: -4px; - .sprite; - .s-sdc-state-non-certified; - display: block; - - &.smaller-icon { - bottom: 6px; - left: 13px; - } - } - - - - } - - .non-certified { - position: relative; - left: 0px; - top: 0px; - .sprite; - .s-sdc-state-non-certified; - display: block; - - &.smaller-icon { - left: 35px; - bottom: -14px; - } - } - /* - .i-sdc-composition-leftbar-section-content-item-icon { - background-image: url('../../../styles/images/resource-icons/default.png'); - // position: absolute; - right: 20px; - top: 10px; - height: 40px; - width: 40px; - background-size: 40px; - } - */ - - .i-sdc-designer-leftbar-section-content-item-info { - display: inline-block; - // margin-left: 10px; - //overflow: hidden; - // vertical-align: middle; - width: 160px; - padding: 0 0 0 10px; - } - - .i-sdc-designer-leftbar-section-content-item-info-title { - .m_13_m; - line-height: 14px; - overflow: hidden; - text-overflow: ellipsis; - max-width: 120px; - display: inline-block; - white-space: nowrap; - vertical-align: bottom; - } - - .i-sdc-designer-leftbar-section-content-item-info-text { - .m_13_r; - line-height: 15px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - } - - .i-sdc-designer-leftbar-section-content-item-info-text-link { - color: @color_s; - text-decoration: underline; - float: right; - position: absolute; - right: 17px; - // bottom: 5px; - } - - // --------------------------------------------------------------------------------------------------- - // Form actions - // --------------------------------------------------------------------------------------------------- - .w-sdc-form-actions-container.add-property { - text-align: center; - width: 100%; - margin-top: 2px; - margin-bottom: 12px; - - .w-sdc-form-action { - width: 245px; - } - .w-sdc-form-action.add-property-add-another { - .bg_a; - margin-left: 35px; - } - .w-sdc-form-action.add-property-done { - margin-left: 312px; - } - .w-sdc-form-action.save { - margin-left: 327px; - margin-bottom: 30px; - } - - } - - // --------------------------------------------------------------------------------------------------- - // Top menu - // --------------------------------------------------------------------------------------------------- - .w-sdc-header-menu { - padding: 25px 0; - text-align: center; - white-space: nowrap; - } - - .i-sdc-header-menu-item { - cursor: pointer; - display: inline-block; - height: 43px; - min-width: 93px; - padding: 0 38px; - position: relative; - vertical-align: middle; - - &::after { - border-right: 1px solid @color_m; - content: ''; - display: block; - height: 43px; - right: 0; - position: absolute; - top: 0; - width: 2px; - } - - &:first-child { - &::before { - border-right: 1px solid @color_m; - content: ''; - display: block; - height: 43px; - left: 0; - position: absolute; - top: 0; - width: 2px; - } - } - } - - .i-sdc-header-menu-item-icon { - display: inline-block; - height: 20px; - width: 28px; - } - - .i-sdc-header-menu-item-label { - .g_1; - line-height: 18px; - } - - .service-path-buttons { - margin-top: 12px; - position: absolute; - right: 70px; - top: 53px; - &.with-sidebar { - right: 380px; - } - } - //Canvas search menu - .w-sdc-search-menu { - position:absolute; - right: 18px; - top:53px; - transition: right 0.2s; - display: flex; - flex-direction: column; - align-items: flex-end; - margin-right:10px; - pointer-events: none; - - & > * { - pointer-events: all; - } - - &.with-sidebar { - right:320px; - } - - .search-with-autocomplete-container.composition-search { - margin-top: 12px; - - .search-bar-input { - width: 250px; - padding:2px 50px 2px 10px; - transition:all 0.4s; - } - .search-bar-container { - position:relative; - } - - &:not(:hover):not(.autocomplete-visible):not(.active){ - border-radius: 0; - box-shadow:none; - - .search-bar-input:not(:focus){ - width: 0px; - padding:0; - border:none; - } - .clear-search-x { - display:none; - } - .search-bar-input:not(:focus) ~ .search-bar-button { - border-radius: 2px; - border:solid 1px #fff; - } - } - } - - .zoom-icons { - border:solid 1px #fff; - border-radius: 2px; - box-shadow: 0px 2px 3.88px 0.12px rgba(0, 0, 0, 0.29); - background-color: rgba(234, 234, 234, 0.88); - background-repeat: no-repeat; - margin-top: 10px; - - &:hover { - cursor:pointer; - } - - &:active { - border:none; - background-color: rgba(31, 171, 223, 0.88); - } - } - } - - // --------------------------------------------------------------------------------------------------- - // Canvas inline menu - // --------------------------------------------------------------------------------------------------- - .w-sdc-canvas-menu-list { - .w-sdc-canvas-menu-item-view { - &::before { - content: ''; - display: inline-block; - - .sprite-new; - .view-icon; - vertical-align: top; - margin: 2px 6px 2px 4px; - } - } - - .w-sdc-canvas-menu-item-delete { - &::before { - content: ''; - display: inline-block; - - .sprite-new; - .delete-icon; - vertical-align: bottom; - margin: 1px 10px 0 7px; - } - } - } -} -/*.right-tab-loader { - border: 16px solid #f3f3f3; !* Light grey *! - border-top: 16px solid #3498db; !* Blue *! - border-radius: 50%; - width: 120px; - height: 120px; - animation: spin 2s linear infinite; -}*/ - -@keyframes spin { - 0% { transform: rotate(0deg); } - 100% { transform: rotate(360deg); } -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts deleted file mode 100644 index 2af341b2c1..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts +++ /dev/null @@ -1,352 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import * as _ from "lodash"; -import { - ArtifactModel, - Service, - IAppConfigurtaion, - Resource, - Component, - ComponentInstance, - ArtifactGroupModel, - IFileDownload -} from "app/models"; -import {ICompositionViewModelScope} from "../../composition-view-model"; -import {ArtifactsUtils, ModalsHandler, ArtifactGroupType} from "app/utils"; -import {GRAPH_EVENTS} from "app/utils/constants"; -import {EventListenerService} from "app/services/event-listener-service"; -import {Dictionary} from "../../../../../../utils/dictionary/dictionary"; - -export interface IArtifactsViewModelScope extends ICompositionViewModelScope { - artifacts:Array; - artifactType:string; - downloadFile:IFileDownload; - isLoading:boolean; - allowDeleteAndUpdateArtifactMap:Dictionary; - getTitle():string; - addOrUpdate(artifact:ArtifactModel):void; - delete(artifact:ArtifactModel):void; - download(artifact:ArtifactModel):void; - openEditEnvParametersModal(artifact:ArtifactModel):void; - getEnvArtifact(heatArtifact:ArtifactModel):any; - getEnvArtifactName(artifact:ArtifactModel):string; - isLicenseArtifact(artifact:ArtifactModel):boolean; - isVfOrPnf():boolean; - //isVFiArtifact(artifact:ArtifactModel):boolean; -} - -export class ResourceArtifactsViewModel { - - static '$inject' = [ - '$scope', - '$filter', - '$state', - 'sdcConfig', - 'ArtifactsUtils', - 'ModalsHandler', - '$q', - 'EventListenerService' - ]; - - constructor(private $scope:IArtifactsViewModelScope, - private $filter:ng.IFilterService, - private $state:any, - private sdcConfig:IAppConfigurtaion, - private artifactsUtils:ArtifactsUtils, - private ModalsHandler:ModalsHandler, - private $q:ng.IQService, - private eventListenerService: EventListenerService) { - - this.initScope(); - } - - - private initArtifactArr = (artifactType:string):void => { - let artifacts:Array = []; - - if (this.$scope.selectedComponent) { - if ('interface' == artifactType) { - let interfaces = this.$scope.currentComponent.interfaces; - if (interfaces && interfaces.standard && interfaces.standard.operations) { - - angular.forEach(interfaces.standard.operations, (operation:any, interfaceName:string):void => { - let item:ArtifactModel = {}; - if (operation.implementation) { - item = operation.implementation; - } - item.artifactDisplayName = interfaceName; - item.artifactLabel = interfaceName; - item.mandatory = false; - artifacts.push(item); - }); - } - } else { - //init normal artifacts, deployment or api artifacts - let artifactsObj:ArtifactGroupModel; - switch (artifactType) { - case "api": - artifactsObj = (this.$scope.currentComponent).serviceApiArtifacts; - break; - case "deployment": - if (!this.$scope.isComponentInstanceSelected()) { - artifactsObj = this.$scope.currentComponent.deploymentArtifacts; - } else { - artifactsObj = this.$scope.currentComponent.selectedInstance.deploymentArtifacts; - } - break; - default: - //artifactsObj = this.$scope.selectedComponent.artifacts; - if (!this.$scope.isComponentInstanceSelected()) { - artifactsObj = this.$scope.currentComponent.artifacts; - } else { - artifactsObj = this.$scope.currentComponent.selectedInstance.artifacts; - } - break; - } - _.forEach(artifactsObj, (artifact:ArtifactModel, key) => { - artifacts.push(artifact); - }); - } - } - this.$scope.artifacts = artifacts; - this.$scope.allowDeleteAndUpdateArtifactMap = new Dictionary(); - _.forEach(this.$scope.artifacts, (artifact:ArtifactModel)=>{ - this.$scope.allowDeleteAndUpdateArtifactMap[artifact.artifactLabel] = this.allowDeleteAndUpdateArtifact(artifact); - }); - this.$scope.isLoading = false; - this.$scope.preventMoveTab(false); - }; - - - private convertToArtifactUrl = (artifactType:string):string => { - - switch (artifactType) { - case 'deployment': - return 'DEPLOYMENT'; - case 'api': - return 'SERVICE_API'; - default: - return 'INFORMATIONAL'; - } - - } - - private loadComponentArtifactIfNeeded = (forceLoad?: boolean) => { - - let onGetComponentArtifactsSuccess = (artifacts:ArtifactGroupModel)=> { - switch (this.$scope.artifactType) { - case 'deployment': - this.$scope.currentComponent.deploymentArtifacts = artifacts; - break; - case 'api': - (this.$scope.currentComponent).serviceApiArtifacts = artifacts; - break; - default: - this.$scope.currentComponent.artifacts = artifacts; - break; - } - this.$scope.isLoading = false; - this.initArtifactArr(this.$scope.artifactType); - } - - let onError = ()=> { - this.$scope.isLoading = false; - }; - - switch (this.$scope.artifactType) { - case 'deployment': - if(forceLoad || !this.$scope.currentComponent.deploymentArtifacts) { - this.$scope.component.getArtifactByGroupType(this.convertToArtifactUrl(this.$scope.artifactType)).then(onGetComponentArtifactsSuccess, onError); - } else { - this.initArtifactArr(this.$scope.artifactType); - } - - break; - case 'api': - if(!(this.$scope.currentComponent).serviceApiArtifacts) { - this.$scope.component.getArtifactByGroupType(this.convertToArtifactUrl(this.$scope.artifactType)).then(onGetComponentArtifactsSuccess, onError); - } else { - this.initArtifactArr(this.$scope.artifactType); - } - break; - default: - if(!this.$scope.currentComponent.artifacts) { - this.$scope.component.getArtifactByGroupType(this.convertToArtifactUrl(this.$scope.artifactType)).then(onGetComponentArtifactsSuccess, onError); - } else { - this.initArtifactArr(this.$scope.artifactType); - } - break; - } - } - private loadArtifacts = (forceLoad?: boolean):void => { - - let onGetInstanceArtifactsSuccess = (artifacts:ArtifactGroupModel)=> { - switch (this.$scope.artifactType) { - case 'deployment': - this.$scope.currentComponent.selectedInstance.deploymentArtifacts = artifacts; - break; - default: - this.$scope.currentComponent.selectedInstance.artifacts = artifacts; - break; - } - this.initArtifactArr(this.$scope.artifactType); - }; - - let onError = ()=> { - this.$scope.isLoading = false; - }; - - this.$scope.isLoading = true; - this.$scope.preventMoveTab(true); - if (this.$scope.isComponentInstanceSelected()) { - this.$scope.component.getComponentInstanceArtifactsByGroupType(this.$scope.component.selectedInstance.uniqueId, this.convertToArtifactUrl(this.$scope.artifactType)).then(onGetInstanceArtifactsSuccess, onError); - } else { - this.loadComponentArtifactIfNeeded(forceLoad); - } - } - - private updateArtifactsIfNeeded = ():void => { - if (this.$scope.artifactType === "deployment") { - this.loadArtifacts(true); - } else { - this.initArtifactArr(this.$scope.artifactType); - } - }; - - private openEditArtifactModal = (artifact:ArtifactModel):void => { - this.ModalsHandler.openArtifactModal(artifact, this.$scope.currentComponent).then(():void => { - this.updateArtifactsIfNeeded(); - }); - }; - - private allowDeleteAndUpdateArtifact = (artifact:ArtifactModel):boolean => { - if(!this.$scope.isViewMode()){ - if(this.$scope.isComponentInstanceSelected()){//is artifact of instance - return !this.$scope.selectedComponent.deploymentArtifacts || !this.$scope.selectedComponent.deploymentArtifacts[artifact.artifactLabel];//if the artifact is not from instance parent - }else{//is artifact of main component - return (!artifact.isHEAT() && !artifact.isThirdParty() && !this.$scope.isLicenseArtifact(artifact)); - } - } - return false; -}; - - private initScope = ():void => { - - this.$scope.isLoading = false; - this.$scope.artifactType = this.artifactsUtils.getArtifactTypeByState(this.$state.current.name); - this.$scope.getTitle = ():string => { - return this.artifactsUtils.getTitle(this.$scope.artifactType, this.$scope.currentComponent); - }; - - // Bug 310499 - user should be unable to delete RI artifact. (also talked to David and agreed this function isn't necessary) - // this.$scope.isVFiArtifact = (artifact:ArtifactModel):boolean=> { - // if (artifact.artifactGroupType === ArtifactGroupType.INFORMATION) {//fix DE256847 - // return this.$scope.currentComponent.artifacts && (!this.$scope.currentComponent.artifacts[artifact.artifactLabel] || !this.$scope.currentComponent.artifacts[artifact.artifactLabel].artifactName); - // } - // return this.$scope.currentComponent.selectedInstance && this.$scope.currentComponent.selectedInstance.deploymentArtifacts && this.$scope.currentComponent.selectedInstance.deploymentArtifacts[artifact.artifactLabel]; - // }; - - this.$scope.addOrUpdate = (artifact:ArtifactModel):void => { - this.artifactsUtils.setArtifactType(artifact, this.$scope.artifactType); - let artifactCopy = new ArtifactModel(artifact); - this.openEditArtifactModal(artifactCopy); - }; - - - this.$scope.delete = (artifact:ArtifactModel):void => { - - let onOk = ():void => { - this.$scope.isLoading = true; - this.artifactsUtils.removeArtifact(artifact, this.$scope.artifacts); - - let success = (responseArtifact:ArtifactModel):void => { - this.initArtifactArr(this.$scope.artifactType); - this.$scope.isLoading = false; - }; - - let error = (error:any):void => { - console.log('Delete artifact returned error:', error); - this.initArtifactArr(this.$scope.artifactType); - this.$scope.isLoading = false; - }; - if (this.$scope.isComponentInstanceSelected()) { - this.$scope.currentComponent.deleteInstanceArtifact(artifact.uniqueId, artifact.artifactLabel).then(success, error); - } else { - this.$scope.currentComponent.deleteArtifact(artifact.uniqueId, artifact.artifactLabel).then(success, error);//TODO simulate error (make sure error returns) - } - }; - let title:string = this.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TITLE"); - let message:string = this.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TEXT", "{'name': '" + artifact.artifactDisplayName + "'}"); - this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk); - }; - - - this.$scope.getEnvArtifact = (heatArtifact:ArtifactModel):any=> { - return _.find(this.$scope.artifacts, (item:ArtifactModel)=> { - return item.generatedFromId === heatArtifact.uniqueId; - }); - }; - - this.$scope.getEnvArtifactName = (artifact:ArtifactModel):string => { - let envArtifact = this.$scope.getEnvArtifact(artifact); - if (envArtifact) { - return envArtifact.artifactDisplayName; - } - }; - - this.$scope.isLicenseArtifact = (artifact:ArtifactModel):boolean => { - let isLicense:boolean = false; - if (this.$scope.component.isResource() && (this.$scope.component).isCsarComponent()) { - isLicense = this.artifactsUtils.isLicenseType(artifact.artifactType); - } - - return isLicense; - }; - - this.$scope.openEditEnvParametersModal = (artifact:ArtifactModel):void => { - this.ModalsHandler.openEditEnvParametersModal(artifact, this.$scope.currentComponent).then(()=> { - this.updateArtifactsIfNeeded(); - }, ()=> { - // ERROR - }); - }; - - this.$scope.isVfOrPnf = ():boolean => { - if (this.$scope.selectedComponent.isResource()) { - let selectedResourceType = (this.$scope.selectedComponent).resourceType; - return selectedResourceType == 'VF' || selectedResourceType == 'PNF'; - } - return false; - } - - this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_NODE_SELECTED, this.loadArtifacts); - this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_GRAPH_BACKGROUND_CLICKED, this.loadArtifacts); - - this.$scope.$on('$destroy', () => { - - this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_NODE_SELECTED, this.loadArtifacts); - this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_GRAPH_BACKGROUND_CLICKED, this.loadArtifacts); - }); - - this.loadArtifacts(); - } -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html deleted file mode 100644 index ec81ed81ee..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html +++ /dev/null @@ -1,84 +0,0 @@ - - - -
    - - - -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    - - - -
    -
    - -
    - Description:{{artifact.description}} -
    -
    - - - - - - - - -
    -
    - -
    - -
    -
    diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts.less b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts.less deleted file mode 100644 index 5256542788..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts.less +++ /dev/null @@ -1,173 +0,0 @@ -.w-sdc-designer-sidebar-tab-content.artifacts { - - .i-sdc-designer-sidebar-section-content-item-artifact.hand { - .hand; - } - - .w-sdc-designer-sidebar-section-content { - padding: 0; - } - .w-sdc-designer-sidebar-section-title { - &.expanded { - margin-bottom: 0; - } - } - - .i-sdc-designer-sidebar-section-content-item-artifact-details { - display: inline-block; - margin-left: 5px; - vertical-align: middle; - width: 180px; - &.heat { - line-height: 18px; - width: 250px; - } - } - - .i-sdc-designer-sidebar-section-content-item-artifact-details-name { - .s_14_r; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - max-width:220px; - display: inline-block; - //text-transform: capitalize; - &.enabled { - &:hover { - .a_7; - font-family: @font-opensans-regular - } - } - - } - - .i-sdc-designer-sidebar-section-content-item-artifact-heat-env { - .g_7; - margin-top: 6px; - line-height: 42px; - padding-top: 10px; - border-top:1px solid #c8cdd1; - .enabled { - &:hover { - .hand; - .a_7; - } - } - } - - .i-sdc-designer-sidebar-section-content-item-artifact-filename { - .g_7; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - max-width: 225px; - display: inline-block; - .bold; - &.enabled { - &:hover { - .a_7; - } - } - } - - - .i-sdc-designer-sidebar-section-content-item-file-link{ - border-left: 1px #848586 solid; - height: 58px; - margin-left: -11px; - margin-top: 11px; - border-top: 1px #848586 solid; - border-bottom: 1px #848586 solid; - width: 12px; - float: left; - } - - .i-sdc-designer-sidebar-section-content-item-artifact-details-desc { - display: none; - line-height: 16px; - word-wrap: break-word; - white-space: normal; - } - - .i-sdc-designer-sidebar-section-content-item-artifact-details-desc-label { - .b_3; - } - - - .i-sdc-designer-sidebar-section-content-item-artifact { - border-bottom: 1px solid #c8cdd1; - padding: 5px 10px 5px 18px; - position: relative; - // line-height: 36px; - min-height: 61px; - //cursor: default; - display: flex; - align-items: center; - - - .i-sdc-designer-sidebar-section-content-item-button { - top: 20px; - line-height: 10px; - } - - &:hover { - //background-color: @color_c; - .bg_c; - transition: all .3s; - - .i-sdc-designer-sidebar-section-content-item-button { - display: block; - - } - - } - } - -} - -///////////////////Lifecycle Management -.i-sdc-designer-sidebar-section-content-item-lm { - .b_7; - border-bottom: 1px solid @color_e; - cursor: pointer; - height: 65px; - padding: 22px 0; - position: relative; - - &:hover { - .bg_c_hover; - margin-left: -10px; - margin-right: -10px; - padding: 22px 10px; - - .i-sdc-designer-sidebar-section-content-item-lm-icon { - right: 16px; - } - } -} - -.i-sdc-designer-sidebar-section-content-item-lm:first-child { - margin-top: -18px; -} - -.i-sdc-designer-sidebar-section-content-item-lm-icon { - position: absolute; - right: 6px; - - //TODO: Replace the icons. - &.icon-view { - background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAJCAYAAAACTR1pAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMDE0IDc5LjE1Njc5NywgMjAxNC8wOC8yMC0wOTo1MzowMiAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjdGMDNBRUJDMDkxNjExRTVCMjRBOEI5QzMxQTlBQjY4IiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjdGMDNBRUJEMDkxNjExRTVCMjRBOEI5QzMxQTlBQjY4Ij4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6N0YwM0FFQkEwOTE2MTFFNUIyNEE4QjlDMzFBOUFCNjgiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6N0YwM0FFQkIwOTE2MTFFNUIyNEE4QjlDMzFBOUFCNjgiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz4U2decAAABRUlEQVR42pyRPUvDUBSG39t2UyyaBgvWQZMqKoFq4lBH0U0UqXSxKPaPieCoWPAPKIgdjG1ohaghOrSR1iaLKMXpmnMhQVfPcLmc8zxwPhjnHFE4rx3eMO/w4rr4+vwQuZHRMcwqClaMVeRnplnEskg8O7/g96YJSZLgBz5+R0bKIAgC6IaBvdKukBP0HJ+cctu2cVCtQsrIUFUVlcp+LE6EItWIIVaIV9c3/PnRRqlcxkJeYV2vi+/hEO/9QSx6b56oEUMsOal6/TacQcXinCpaGE+n0QnljufFIuUoiAlZTk6iWFyD6zpoWi3RwvrmBlLJZCzRn3IUxBBLjlgO9e06T9ja3sGyrqPX66NtWQLWCgVks5Owmg1c1mpQ8vM4OqywP1s1w1PkpnJY0jTIsizy/sDHQ7sFmt0ITxJtlf33jj8CDADhB52tEX6ifAAAAABJRU5ErkJggg=='); - height: 9px; - top: 29px; - width: 14px; - } - - //TODO: Replace the icons. - &.icon-alert { - background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA8AAAANCAYAAAB2HjRBAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMDE0IDc5LjE1Njc5NywgMjAxNC8wOC8yMC0wOTo1MzowMiAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjhBM0YxQTBCMDkyMDExRTVBNzlCQUYxNEYwMDUwOTQ5IiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjhBM0YxQTBDMDkyMDExRTVBNzlCQUYxNEYwMDUwOTQ5Ij4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6OEEzRjFBMDkwOTIwMTFFNUE3OUJBRjE0RjAwNTA5NDkiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6OEEzRjFBMEEwOTIwMTFFNUE3OUJBRjE0RjAwNTA5NDkiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7exgceAAAB5klEQVR42oySy2tTQRTGfzN3cpvbpFTaUlzUjeCuVFyJf4DuCl34wL/CrbpUunLnwpUuFFy48IFiwYWhpYuW+gCLrbWKBQumaRIba5ub3MccJ5WECCV44MDMme873/lmBhGhnZulcn/3/sfrO7J/45R017pT0xUS2bC93vy2LAOLt5DfCeUn14RD4h/ysbHRDii/8pyo7DmFiP7VZ4Rbu9KT3I7i+qJklp7ibQt2J6HeNOhXV/gv8tDcbaLtXYLJKeTcZfxqSPPzvGu6ID3J1Q8z0ny/hIkM5swF8qenUFUfwixHCtd7Kwez04jOgEmc+hq6tuZ8N9E6xG5U+Pn2kRxKLs7eE7tRc0XlToRM2sD+2sGmDiY+kWsSFG528Kr1Xgfjfn0n5uElvFrrzVqVDHqkiTKjxCsV9LBx08QkgcY/eZH+89Oqo+x9eumkwQaQaoPEKWpsHHN8ArItgLt5UdiG6736mFLxixyQt+bviik8QPuaNFRIkjqQRZ2YJDo6QWydjTRtOcGPPdJKgnlxFfN9fVmGNhecR4U3mLrL6nPTRTQHXZO5+4jyyI4Iqs99GJvgBiKjcySlj3897y6/kbreI4w0QS7ASxrsa4/cXkxkIzK5PKmNqRMw7NfdeczA+Fn1R4ABAPnMAeCjkgf5AAAAAElFTkSuQmCC'); - height: 13px; - top: 27px; - width: 15px; - } - -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts deleted file mode 100644 index 36ceabfb42..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts +++ /dev/null @@ -1,201 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import * as _ from "lodash"; -import {Component, ModalModel, ButtonModel} from "app/models"; -import {GRAPH_EVENTS} from "app/utils"; -import {LeftPaletteLoaderService, EventListenerService} from "app/services"; -import {ICompositionViewModelScope} from "../../composition-view-model"; -import {LeftPaletteComponent} from "../../../../../../models/components/displayComponent"; -import {ComponentServiceFactoryNg2} from "app/ng2/services/component-services/component.service.factory"; -import {ServiceServiceNg2} from 'app/ng2/services/component-services/service.service'; -import {Service} from "app/models/components/service"; -import {ModalService} from 'app/ng2/services/modal.service'; - -export interface IEditResourceVersion { - allVersions:any; - changeVersion:string; -} - -interface IDetailsViewModelScope extends ICompositionViewModelScope { - isLoading:boolean; - $parent:ICompositionViewModelScope; - expandedSection:Array; - editForm:ng.IFormController; - editResourceVersion:IEditResourceVersion; - - onChangeResourceVersion():void; - alertBeforeChangeResourceVersion():void; - changeVersion():void; - cancelChangeResourceVersion():void; -} - -export class DetailsViewModel { - - static '$inject' = [ - '$scope', - '$filter', - 'LeftPaletteLoaderService', - 'EventListenerService', - 'ComponentServiceFactoryNg2', - 'ServiceServiceNg2', - 'ModalServiceNg2' - ]; - - constructor(private $scope:IDetailsViewModelScope, - private $filter:ng.IFilterService, - private LeftPaletteLoaderService:LeftPaletteLoaderService, - private eventListenerService:EventListenerService, - private ComponentServiceFactoryNg2: ComponentServiceFactoryNg2, - private serviceService: ServiceServiceNg2, - private ModalServiceNg2: ModalService) { - this.initScope(); - } - - private clearSelectedVersion = ():void => { - this.$scope.editResourceVersion = { - allVersions: {}, - changeVersion: null - }; - }; - - private versioning:Function = (versionNumber:string):string => { - let version:Array = versionNumber.split('.'); - return '00000000'.slice(version[0].length) + version[0] + '.' + '00000000'.slice(version[1].length) + version[1]; - }; - - private initEditResourceVersion = ():void => { - this.clearSelectedVersion(); - this.$scope.editResourceVersion.allVersions[this.$scope.currentComponent.selectedInstance.componentVersion] = this.$scope.currentComponent.selectedInstance.componentUid; - _.merge(this.$scope.editResourceVersion.allVersions, angular.copy(this.$scope.selectedComponent.allVersions)); - let sorted:any = _.sortBy(_.toPairs(this.$scope.editResourceVersion.allVersions), (item)=> { - return this.versioning(item[0]); - }); - this.clearSelectedVersion(); - _.forEach(sorted, (item)=> { - this.$scope.editResourceVersion.allVersions[item[0]] = item[1]; - }); - - let highestVersion = _.last(Object.keys(this.$scope.selectedComponent.allVersions)); - - if (parseFloat(highestVersion) % 1) { //if highest is minor, make sure it is the latest checked in - - let latestVersionComponent:LeftPaletteComponent = _.maxBy(_.filter(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(this.$scope.currentComponent), (component:LeftPaletteComponent) => { //latest checked in - return (component.systemName === this.$scope.selectedComponent.systemName - || component.uuid === this.$scope.selectedComponent.uuid); - }),(component)=>{return component.version}); - - let latestVersion:string = latestVersionComponent ? latestVersionComponent.version : highestVersion; - - if (highestVersion != latestVersion) { //highest is checked out - remove from options - this.$scope.editResourceVersion.allVersions = _.omit(this.$scope.editResourceVersion.allVersions, highestVersion); - } - } - this.$scope.editResourceVersion.changeVersion = this.$scope.currentComponent.selectedInstance.componentVersion; - }; - - private initScope = ():void => { - this.$scope.isLoading = false; - this.$scope.$parent.isLoading = false; - this.$scope.expandedSection = ['general', 'tags']; - //this.clearSelectedVersion(); - - this.$scope.$watch('selectedComponent', (component:Component) => { - if (this.$scope.isComponentInstanceSelected()) { - this.initEditResourceVersion(); - } - }); - - this.$scope.onChangeResourceVersion = ():void => { - if(this.$scope.isComponentInstanceSelected() && this.$scope.currentComponent.selectedInstance.isServiceProxy()) { - this.$scope.alertBeforeChangeResourceVersion(); - } - else { - this.$scope.changeVersion(); - } - }; - - this.$scope.alertBeforeChangeResourceVersion = ():void => { - let modalApproveTxt:string = this.$filter('translate')("MODAL_APPROVE"); - let modalCancelTxt:string = this.$filter('translate')("MODAL_CANCEL"); - let changeVersionModalTitle:string = this.$filter('translate')("DETAILS_TAB_CHANGE_VERSION_MODAL_TITLE"); - let changeVersionModalMsg:string = this.$filter('translate')("DETAILS_TAB_CHANGE_VERSION_MODAL_MSG"); - - let actionButton: ButtonModel = new ButtonModel(modalApproveTxt, 'blue', this.$scope.changeVersion); - let cancelButton: ButtonModel = new ButtonModel(modalCancelTxt, 'grey', this.$scope.cancelChangeResourceVersion); - let modalModel: ModalModel = new ModalModel('sm', changeVersionModalTitle, changeVersionModalMsg, [actionButton, cancelButton]); - let customModal = this.ModalServiceNg2.createCustomModal(modalModel); - customModal.instance.open(); - }; - - this.$scope.cancelChangeResourceVersion = () => { - this.ModalServiceNg2.closeCurrentModal(); - this.$scope.editResourceVersion.changeVersion = this.$scope.currentComponent.selectedInstance.componentVersion; - }; - - this.$scope.changeVersion = ():void => { - this.ModalServiceNg2.closeCurrentModal(); - this.$scope.isLoading = true; - this.$scope.$parent.isLoading = true; - - let service = this.$scope.currentComponent; - let {changeVersion} = this.$scope.editResourceVersion; - let componentUid:string = this.$scope.editResourceVersion.allVersions[changeVersion]; - - let onCancel = (error:any) => { - this.$scope.isLoading = false; - this.$scope.$parent.isLoading = false; - this.$scope.editResourceVersion.changeVersion = this.$scope.currentComponent.selectedInstance.componentVersion; - - if (error) { - console.log(error); - } - }; - - let onUpdate = () => { - let onSuccess = (component:Component) => { - this.$scope.isLoading = false; - this.$scope.$parent.isLoading = false; - this.$scope.onComponentInstanceVersionChange(component); - }; - - this.$scope.currentComponent.changeComponentInstanceVersion(componentUid).then(onSuccess, onCancel); - }; - - if (this.$scope.currentComponent.isService()) { - this.serviceService.checkComponentInstanceVersionChange(service, componentUid).subscribe((pathsToDelete:string[]) => { - if (pathsToDelete && pathsToDelete.length) { - this.$scope.isLoading = false; - this.$scope.$parent.isLoading = false; - this.$scope.$parent.openVersionChangeModal(pathsToDelete).then(() => { - this.$scope.isLoading = true; - this.$scope.$parent.isLoading = true; - onUpdate(); - }, onCancel); - } else { - onUpdate(); - } - }, onCancel); - } else { - onUpdate(); - } - }; - } -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view.html deleted file mode 100644 index db5322a859..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view.html +++ /dev/null @@ -1,181 +0,0 @@ - - - - -
    - - - - General Info -
    -
    - -
    -
    - Type: - -
    -
    - Resource Type: - -
    -
    - - Version: - - - - -
    -
    - Category: - -
    -
    - Sub Category: - -
    -
    - Creation Date: - -
    -
    - Author: - - -
    -
    - - -
    -
    - Vendor Name: - - -
    -
    - Vendor Release: - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - -
    - -
    - - -
    - -
    -
    -
    -
    -
    - Description: - - - -
    - -
    -
    - -
    - - Additional Information -
    -
    - -
    -
    - - : - -
    -
    -
    - - -
    - - Tags -
    -
    - -
    -
    - - -
    -
    -
    -
    - - - diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details.less b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details.less deleted file mode 100644 index 90bb5658c8..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details.less +++ /dev/null @@ -1,81 +0,0 @@ -.w-sdc-designer-sidebar-tab-content.details { - - .w-sdc-designer-sidebar-section-title + .w-sdc-designer-sidebar-section-content { - padding: 0 10px 0 18px; - } - - .w-sdc-designer-sidebar-section-title.expanded + .w-sdc-designer-sidebar-section-content { - padding: 10px 10px 10px 18px; - } - - .i-sdc-designer-sidebar-section-content-item-label { - font-family: @font-opensans-medium; - color: #191919; - font-size: 13px; - &.additional-information{ - max-width:100px; - display: inline-block; - text-overflow: ellipsis; - overflow: hidden; - vertical-align: bottom; - } - - } - - - - .i-sdc-designer-sidebar-section-content-item-value { - // .hyphenate; - font-family: @font-opensans-regular; - color: #191919; - font-size: 13px; - padding-left: 10px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - //display: inline-block; fix long name for firefox - max-width: 160px; - vertical-align:bottom; - font-weight: normal; - &.vendor-model-number{ - max-width: 110px; - } - &.additional-information{ - max-width:160px; - display: inline-block; - } - &.i-sdc-form-select { - .b_1; - border: 1px solid @border_color_f; - width: 210px; - max-width: 210px; - padding-left: 4px; - - .select-instance-version { - .b_1; - &.minor { - .h_1; - } - } - } - &.minor { - .h_1; - } - } - .i-sdc-designer-sidebar-section-content-description-item-value{ - max-width: none; - font-weight: normal; - font-family: @font-opensans-regular; - } - - .customization-uuid{ - .f-type._12_m; - } - - .w-sdc-designer-sidebar-section.tags { - .i-sdc-designer-sidebar-section-content-item { - white-space: normal; - } - } - -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view-model.ts deleted file mode 100644 index e3ddecd9a5..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view-model.ts +++ /dev/null @@ -1,244 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import * as _ from "lodash"; -import { - AttributeModel, - AttributesGroup, - Component, - ComponentInstance, - PropertyModel, - PropertiesGroup -} from "app/models"; -import {ICompositionViewModelScope} from "../../composition-view-model"; -import {ModalsHandler} from "app/utils"; -import {ComponentServiceNg2} from "app/ng2/services/component-services/component.service"; -import {ComponentGenericResponse} from "app/ng2/services/responses/component-generic-response"; - -interface IResourcePropertiesAndAttributesViewModelScope extends ICompositionViewModelScope { - properties:PropertiesGroup; - attributes:AttributesGroup; - propertiesMessage:string; - groupPropertiesByInstance:boolean; - showGroupsOfInstanceProperties:Array; - addProperty():void; - updateProperty(property:PropertyModel):void; - deleteProperty(property:PropertyModel):void; - viewAttribute(attribute:AttributeModel):void; - groupNameByKey(key:string):string; - isPropertyOwner():boolean; - getComponentInstanceNameFromInstanceByKey(key:string):string; -} - -export class ResourcePropertiesViewModel { - - static '$inject' = [ - '$scope', - '$filter', - '$uibModal', - 'ModalsHandler', - 'ComponentServiceNg2' - - ]; - - - constructor(private $scope:IResourcePropertiesAndAttributesViewModelScope, - private $filter:ng.IFilterService, - private $uibModal:ng.ui.bootstrap.IModalService, - private ModalsHandler:ModalsHandler, - private ComponentServiceNg2:ComponentServiceNg2) { - - this.getComponentInstancesPropertiesAndAttributes(); - } - - private initComponentProperties = ():void => { - let result:PropertiesGroup = {}; - - if (this.$scope.selectedComponent) { - this.$scope.propertiesMessage = undefined; - this.$scope.groupPropertiesByInstance = false; - if (this.$scope.isComponentInstanceSelected()) { - if (this.$scope.currentComponent.selectedInstance.originType === 'VF') { - this.$scope.groupPropertiesByInstance = true; - } - result[this.$scope.currentComponent.selectedInstance.uniqueId] = this.$scope.currentComponent.componentInstancesProperties[this.$scope.currentComponent.selectedInstance.uniqueId]; - } else if (this.$scope.currentComponent.isService()) { - // Temporally fix to hide properties for service (UI stack when there are many properties) - result = this.$scope.currentComponent.componentInstancesProperties; - this.$scope.propertiesMessage = "Note: properties for service are disabled"; - } else { - let key = this.$scope.selectedComponent.uniqueId; - result[key] = Array(); - let derived = Array(); - _.forEach(this.$scope.selectedComponent.properties, (property:PropertyModel) => { - if (key == property.parentUniqueId) { - result[key].push(property); - } else { - property.readonly = true; - derived.push(property); - } - }); - if (derived.length) { - result['derived'] = derived; - } - } - this.$scope.properties = result; - } - }; - - - private initComponentAttributes = ():void => { - let result:AttributesGroup = {}; - - if (this.$scope.selectedComponent) { - if (this.$scope.isComponentInstanceSelected()) { - result[this.$scope.currentComponent.selectedInstance.uniqueId] = this.$scope.currentComponent.componentInstancesAttributes[this.$scope.currentComponent.selectedInstance.uniqueId]; - } else if (this.$scope.currentComponent.isService()) { - result = this.$scope.currentComponent.componentInstancesAttributes; - } - this.$scope.attributes = result; - } - }; - - /** - * This function is checking if the component is the value owner of the current property - * in order to notify the edit property modal which fields to disable - */ - private isPropertyValueOwner = ():boolean => { - return this.$scope.currentComponent.isService() || !!this.$scope.currentComponent.selectedInstance; - }; - - /** - * The function opens the edit property modal. - * It checks if the property is from the VF or from one of it's resource instances and sends the needed property list. - * For create property reasons an empty array is transferd - * - * @param property the wanted property to edit/create - */ - private openEditPropertyModal = (property:PropertyModel):void => { - this.ModalsHandler.openEditPropertyModal(property, - this.$scope.component, - (this.$scope.isPropertyOwner() ? - this.$scope.properties[property.parentUniqueId] : - this.$scope.properties[property.resourceInstanceUniqueId]) || [], - this.isPropertyValueOwner(), "component", property.resourceInstanceUniqueId).then((updatedProperty:PropertyModel) => { - if(updatedProperty){ - let oldProp = _.find(this.$scope.properties[updatedProperty.resourceInstanceUniqueId], (prop:PropertyModel) => {return prop.uniqueId == updatedProperty.uniqueId;}); - oldProp.value = updatedProperty.value; - } - }); - }; - - private openAttributeModal = (atrribute:AttributeModel):void => { - - let modalOptions:ng.ui.bootstrap.IModalSettings = { - template: 'app/view-models/forms/attribute-form/attribute-form-view.html', - controller: 'Sdc.ViewModels.AttributeFormViewModel', - size: 'sdc-md', - backdrop: 'static', - keyboard: false, - resolve: { - attribute: ():AttributeModel => { - return atrribute; - }, - component: ():Component => { - return this.$scope.currentComponent; - } - } - }; - this.$uibModal.open(modalOptions); - }; - - private getComponentInstancesPropertiesAndAttributes = () => { - - this.ComponentServiceNg2.getComponentInstanceAttributesAndProperties(this.$scope.currentComponent).subscribe((genericResponse:ComponentGenericResponse) => { - this.$scope.currentComponent.componentInstancesAttributes = genericResponse.componentInstancesAttributes; - this.$scope.currentComponent.componentInstancesProperties = genericResponse.componentInstancesProperties; - this.initScope(); - }); - }; - - private initScope = ():void => { - - - this.initComponentProperties(); - this.initComponentAttributes(); - - this.$scope.$watchCollection('currentComponent.properties', (newData:any):void => { - this.initComponentProperties(); - }); - - this.$scope.$watch('currentComponent.selectedInstance', (newInstance:ComponentInstance):void => { - if (angular.isDefined(newInstance)) { - this.initComponentProperties(); - this.initComponentAttributes(); - - } - }); - - this.$scope.isPropertyOwner = ():boolean => { - return this.$scope.currentComponent && this.$scope.currentComponent.isResource() && !this.$scope.isComponentInstanceSelected(); - }; - - this.$scope.updateProperty = (property:PropertyModel):void => { - this.openEditPropertyModal(property); - }; - - this.$scope.deleteProperty = (property:PropertyModel):void => { - - let onOk = ():void => { - this.$scope.currentComponent.deleteProperty(property.uniqueId); - }; - - let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE"); - let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}"); - this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk); - }; - - this.$scope.viewAttribute = (attribute:AttributeModel):void => { - this.openAttributeModal(attribute); - }; - - this.$scope.groupNameByKey = (key:string):string => { - switch (key) { - case 'derived': - return "Derived"; - - case this.$scope.currentComponent.uniqueId: - return this.$filter("resourceName")(this.$scope.currentComponent.name); - - default: - let componentInstance = _.find(this.$scope.currentComponent.componentInstances, {uniqueId: key}); - if(componentInstance) - return this.$filter("resourceName")(componentInstance.name); - } - }; - - this.$scope.getComponentInstanceNameFromInstanceByKey = (key:string):string => { - let instanceName:string = ""; - if (key !== undefined && this.$scope.selectedComponent.uniqueId == this.$scope.currentComponent.selectedInstance.componentUid) { - instanceName = this.$filter("resourceName")((_.find(this.$scope.selectedComponent.componentInstances, {uniqueId: key})).name); - } - return instanceName; - }; - - } -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view.html deleted file mode 100644 index cdd69682dc..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view.html +++ /dev/null @@ -1,133 +0,0 @@ - - - - -
    - - - - -
    -
    - -
    -
    - -
    -
    -
    -
    - {{property.name}} -
    -
    - {{property.defaultValue}} - {{property.value}} -
    - -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    - {{instanceProperty.name}} -
    -
    - - {{instanceProperty.value === undefined ? instanceProperty.defaultValue : instanceProperty.value}} -
    -
    -
    -
    -
    - - - - - -
    - - - - -
    -
    - -
    -
    - -
    -
    -
    -
    - {{attribute.name}} -
    -
    - {{attribute.defaultValue}} - {{attribute.value}} -
    -
    -
    - -
    - -
    -
    diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties.less b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties.less deleted file mode 100644 index ce5acc83e5..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties.less +++ /dev/null @@ -1,39 +0,0 @@ -.w-sdc-designer-sidebar-tab-content.properties { - .i-sdc-designer-sidebar-section-content-item-property-and-attribute-label{ - display:block; - font-weight: bold; - } - .i-sdc-designer-sidebar-section-content-item-button.update{ - right: 17px; - } - .i-sdc-designer-sidebar-section-content-item-button.delete{ - right: 35px; - } - - .w-sdc-designer-sidebar-properties-disabled { - .s_14_m; - padding: 20px 20px; - } - - .vfci-properties-group{ - background-color: @func_color_r; - } - - .expand-collapse-title-icon{ - .hand; - .sprite-new; - .expand-collapse-plus-icon; - vertical-align: middle; - margin: 0 6px; - } - - .expanded { - .expand-collapse-title-icon { - .expand-collapse-minus-icon; - } - } - - .w-sdc-designer-sidebar-section-title-text{ - vertical-align: middle; - } -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations-view-model.ts deleted file mode 100644 index ce44aaff50..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations-view-model.ts +++ /dev/null @@ -1,177 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import * as _ from "lodash"; -import {ICompositionViewModelScope} from "../../composition-view-model"; -import {CapabilitiesGroup, Requirement, RequirementsGroup} from "app/models"; -import {ComponentServiceNg2} from "app/ng2/services/component-services/component.service"; -import {ComponentGenericResponse} from "app/ng2/services/responses/component-generic-response"; -import {GRAPH_EVENTS} from "app/utils"; -import {EventListenerService} from "app/services"; -import {ComponentInstance, Capability} from "app/models"; - -interface IRelationsViewModelScope extends ICompositionViewModelScope { - isLoading:boolean; - $parent:ICompositionViewModelScope; - getRelation(requirement:any):any; - capabilities:Array; - requirements:Array; - - //for complex components - capabilitiesInstancesMap:InstanceCapabilitiesMap; - requirementsInstancesMap:InstanceRequirementsMap; -} -export class InstanceCapabilitiesMap { - [key:string]:Array; -} - -export class InstanceRequirementsMap { - [key:string]:Array; -} - -export class RelationsViewModel { - - static '$inject' = [ - '$scope', - '$filter', - 'ComponentServiceNg2', - 'EventListenerService' - ]; - - constructor(private $scope:IRelationsViewModelScope, - private $filter:ng.IFilterService, - private ComponentServiceNg2:ComponentServiceNg2, - private eventListenerService:EventListenerService) { - this.initScope(); - } - - private loadComplexComponentData = () => { - this.$scope.isLoading = true; - this.ComponentServiceNg2.getCapabilitiesAndRequirements(this.$scope.currentComponent.componentType, this.$scope.currentComponent.uniqueId).subscribe((response:ComponentGenericResponse) => { - this.$scope.currentComponent.capabilities = response.capabilities; - this.$scope.currentComponent.requirements = response.requirements; - this.setScopeCapabilitiesRequirements(this.$scope.currentComponent.capabilities, this.$scope.currentComponent.requirements); - this.initInstancesMap(); - this.$scope.isLoading = false; - }); - } - - - private extractValuesFromMap = (map:CapabilitiesGroup | RequirementsGroup):Array => { - let values = []; - _.forEach(map, (capabilitiesOrRequirements:Array | Array, key) => { - values = values.concat(capabilitiesOrRequirements) - } - ); - return values; - } - - private setScopeCapabilitiesRequirements = (capabilities:CapabilitiesGroup, requirements:RequirementsGroup) => { - this.$scope.capabilities = this.extractValuesFromMap(capabilities); - this.$scope.requirements = this.extractValuesFromMap(requirements); - } - - - private initInstancesMap = ():void => { - - this.$scope.capabilitiesInstancesMap = new InstanceCapabilitiesMap(); - _.forEach(this.$scope.capabilities, (capability:Capability) => { - if (this.$scope.capabilitiesInstancesMap[capability.ownerName]) { - this.$scope.capabilitiesInstancesMap[capability.ownerName] = this.$scope.capabilitiesInstancesMap[capability.ownerName].concat(capability); - } else { - this.$scope.capabilitiesInstancesMap[capability.ownerName] = new Array(capability); - } - }); - - this.$scope.requirementsInstancesMap = new InstanceRequirementsMap(); - _.forEach(this.$scope.requirements, (requirement:Requirement) => { - if (this.$scope.requirementsInstancesMap[requirement.ownerName]) { - this.$scope.requirementsInstancesMap[requirement.ownerName] = this.$scope.requirementsInstancesMap[requirement.ownerName].concat(requirement); - } else { - this.$scope.requirementsInstancesMap[requirement.ownerName] = new Array(requirement); - } - }); - } - - private initRequirementsAndCapabilities = (needUpdate?: boolean) => { - - // if instance selected, we take the requirement and capabilities of the instance - always exist because we load them with the graph - if (this.$scope.isComponentInstanceSelected()) { - this.$scope.isLoading = false; - this.setScopeCapabilitiesRequirements(this.$scope.currentComponent.selectedInstance.capabilities, this.$scope.currentComponent.selectedInstance.requirements); - if (this.$scope.currentComponent.selectedInstance.originType === 'VF') { - this.initInstancesMap(); - } - } else { - // if instance not selected, we take the requirement and capabilities of the VF/SERVICE, if not exist we call api - if (needUpdate || !this.$scope.currentComponent.capabilities || !this.$scope.currentComponent.requirements) { - this.loadComplexComponentData(); - - } else { - this.$scope.isLoading = false; - this.setScopeCapabilitiesRequirements(this.$scope.currentComponent.capabilities, this.$scope.currentComponent.requirements); - this.initInstancesMap(); - } - } - } - - private updateRequirementCapabilities = () => { - if (!this.$scope.isComponentInstanceSelected()) { - this.loadComplexComponentData(); - } - } - - private initEvents = ():void => { - this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_NODE_SELECTED, this.initRequirementsAndCapabilities); - this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_GRAPH_BACKGROUND_CLICKED, this.updateRequirementCapabilities); - this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_CREATE_COMPONENT_INSTANCE, this.updateRequirementCapabilities); - this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_DELETE_COMPONENT_INSTANCE, this.updateRequirementCapabilities); - } - - private initScope = ():void => { - - this.$scope.requirements = []; - this.$scope.capabilities = []; - - this.initEvents(); - this.initRequirementsAndCapabilities(); - - this.$scope.isCurrentDisplayComponentIsComplex = ():boolean => { - if (this.$scope.isComponentInstanceSelected()) { - if (this.$scope.currentComponent.selectedInstance.originType === 'VF') { - return true; - } - return false; - } else { - return this.$scope.currentComponent.isComplex(); - } - } - - this.$scope.$on('$destroy', () => { - - this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_NODE_SELECTED, this.initRequirementsAndCapabilities); - this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_GRAPH_BACKGROUND_CLICKED, this.updateRequirementCapabilities); - this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_CREATE_COMPONENT_INSTANCE, this.updateRequirementCapabilities); - this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_DELETE_COMPONENT_INSTANCE, this.updateRequirementCapabilities); - }); - - } -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations-view.html deleted file mode 100644 index 889f129dac..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations-view.html +++ /dev/null @@ -1,77 +0,0 @@ - - - -
    -
    - Capabilities -
    -
    -
    - -
    -
    -
    - Requirements -
    -
    - -
    - -
    -
    -
    - -
    -
    - Capabilities -
    -
    -
    -
    - -
    -
    - -
    -
    - -
    - -
    -
    - -
    - Requirements -
    -
    -
    -
    - -
    -
    - -
    -
    - -
    - -
    -
    -
    -
    diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations.less b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations.less deleted file mode 100644 index c3b224d5a6..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations.less +++ /dev/null @@ -1,14 +0,0 @@ -.w-sdc-designer-sidebar-tab-content.relations { - - .w-sdc-designer-sidebar-section-content { - padding: 0; - } - - .w-sdc-designer-sidebar-section-title { - &.expanded { - margin-bottom: 0; - } - } -} - - diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/service-consumption/service-consumption-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/service-consumption/service-consumption-view-model.ts deleted file mode 100644 index 737002303b..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/service-consumption/service-consumption-view-model.ts +++ /dev/null @@ -1,101 +0,0 @@ -/*! -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express -* or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - - -import {ICompositionViewModelScope} from "../../composition-view-model"; -import { - Service, - PropertiesGroup, - InputsGroup, - ServiceInstanceObject, - InterfaceModel, - InputBEModel, - CapabilitiesGroup, - Capability, - ComponentInstance -} from 'app/models'; -import {ComponentGenericResponse} from "app/ng2/services/responses/component-generic-response"; -import {ServiceServiceNg2} from "app/ng2/services/component-services/service.service"; - -interface IServiceConsumptionViewModelScope extends ICompositionViewModelScope { - service: Service; - instancesMappedList: Array; - componentInstancesProperties: PropertiesGroup; - componentInstancesInputs: InputsGroup; - componentInstancesInterfaces: Map>; - componentInputs: Array; - componentCapabilities: Array; - instancesCapabilitiesMap: Map>; -} - - -export class ServiceConsumptionViewModel { - - static '$inject' = [ - '$scope', - 'ServiceServiceNg2' - ]; - - constructor(private $scope:IServiceConsumptionViewModelScope, private ServiceServiceNg2:ServiceServiceNg2) { - this.$scope.service = this.$scope.currentComponent; - this.initInstances(); - this.initScope(); - } - - private initInstances = ():void => { - this.ServiceServiceNg2.getServiceConsumptionData(this.$scope.service).subscribe((genericResponse:ComponentGenericResponse) => { - this.$scope.componentInstancesProperties = genericResponse.componentInstancesProperties; - this.$scope.componentInstancesInputs = genericResponse.componentInstancesInputs; - this.$scope.componentInstancesInterfaces = genericResponse.componentInstancesInterfaces; - this.$scope.componentInputs = genericResponse.inputs; - this.buildInstancesCapabilitiesMap(genericResponse.componentInstances); - this.updateInstanceAttributes(); - }); - } - - buildInstancesCapabilitiesMap = (componentInstances: Array): void => { - this.$scope.instancesCapabilitiesMap = new Map(); - let flattenCapabilities = []; - _.forEach(componentInstances, componentInstance => { - flattenCapabilities = CapabilitiesGroup.getFlattenedCapabilities(componentInstance.capabilities); - this.$scope.instancesCapabilitiesMap[componentInstance.uniqueId] = _.filter(flattenCapabilities, cap => cap.properties && cap.ownerId === componentInstance.uniqueId); - }); - } - - private updateInstanceAttributes = ():void => { - if (this.$scope.isComponentInstanceSelected() && this.$scope.componentInstancesProperties) { - this.$scope.instancesMappedList = this.$scope.service.componentInstances.map(coInstance => new ServiceInstanceObject({ - id: coInstance.uniqueId, - name: coInstance.name, - properties: this.$scope.componentInstancesProperties[coInstance.uniqueId] || [], - inputs: this.$scope.componentInstancesInputs[coInstance.uniqueId] || [], - interfaces: this.$scope.componentInstancesInterfaces[coInstance.uniqueId] || [] - })); - } - } - - private initScope = ():void => { - this.$scope.$watch('currentComponent.selectedInstance', ():void => { - this.updateInstanceAttributes(); - }); - - this.$scope.registerCreateInstanceEvent(() => { - this.initInstances(); - }); - - this.$scope.$on('$destroy', this.$scope.unregisterCreateInstanceEvent); - } -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/service-consumption/service-consumption-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/service-consumption/service-consumption-view.html deleted file mode 100644 index 8404a7f653..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/service-consumption/service-consumption-view.html +++ /dev/null @@ -1,23 +0,0 @@ - -
    - - Operation Consumption -
    -
    - -
    -
    - - -
    -
    -
    -
    \ No newline at end of file diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/service-dependencies/service-dependencies-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/service-dependencies/service-dependencies-view-model.ts deleted file mode 100644 index b634e6021f..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/service-dependencies/service-dependencies-view-model.ts +++ /dev/null @@ -1,125 +0,0 @@ -/*! - * Copyright © 2016-2018 European Support Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - - -import {ICompositionViewModelScope} from "../../composition-view-model"; -import {Service, ComponentInstance, PropertiesGroup, ServiceInstanceObject, PropertyBEModel} from 'app/models'; -import {ComponentServiceNg2} from "app/ng2/services/component-services/component.service"; -import {ConstraintObject} from "app/ng2/components/logic/service-dependencies/service-dependencies.component"; -import {ComponentGenericResponse} from 'app/ng2/services/responses/component-generic-response'; -import {DEPENDENCY_EVENTS} from "app/utils/constants"; -import {EventListenerService} from 'app/services'; - -interface IServiceDependenciesViewModelScope extends ICompositionViewModelScope { - service: Service; - selectedInstanceSiblings: Array; - componentInstancesConstraints: Array; - selectedInstanceConstraints: Array; - selectedInstanceProperties: Array; - updateSelectedInstanceConstraints(constraintsList:Array): void; - loadConstraints(): void; - componentInstanceProperties: PropertiesGroup; - notifyDependencyEventsObserver: Function; -} - - - -export class ServiceDependenciesViewModel { - - static '$inject' = [ - '$scope', - 'ComponentServiceNg2', - 'EventListenerService' - ]; - - constructor(private $scope:IServiceDependenciesViewModelScope, private ComponentServiceNg2:ComponentServiceNg2, private eventListenerService: EventListenerService) { - this.$scope.service = this.$scope.currentComponent; - this.$scope.notifyDependencyEventsObserver = this.notifyDependencyEventsObserver; - this.initInstancesWithProperties(); - this.loadConstraints(); - - this.initScope(); - } - - private initInstancesWithProperties = ():void => { - this.ComponentServiceNg2.getComponentInstanceProperties(this.$scope.currentComponent).subscribe((genericResponse:ComponentGenericResponse) => { - this.$scope.componentInstanceProperties = genericResponse.componentInstancesProperties; - this.updateInstanceAttributes(); - }); - } - - private updateInstanceAttributes = ():void => { - if (this.$scope.isComponentInstanceSelected() && this.$scope.componentInstanceProperties) { - let instancesMappedList = this.$scope.service.componentInstances.map(coInstance => new ServiceInstanceObject({ - id: coInstance.uniqueId, - name: coInstance.name, - properties: this.$scope.componentInstanceProperties[coInstance.uniqueId] || [] - })); - this.$scope.selectedInstanceProperties = this.$scope.componentInstanceProperties[this.$scope.currentComponent.selectedInstance.uniqueId]; - this.$scope.selectedInstanceSiblings = instancesMappedList.filter(coInstance => coInstance.id !== this.$scope.currentComponent.selectedInstance.uniqueId); - } - } - - private initScope = ():void => { - this.$scope.$watch('currentComponent.selectedInstance', (newInstance:ComponentInstance):void => { - if (angular.isDefined(newInstance) && this.$scope.componentInstancesConstraints) { - this.updateInstanceAttributes(); - this.$scope.selectedInstanceConstraints = this.$scope.componentInstancesConstraints[this.$scope.currentComponent.selectedInstance.uniqueId] ? - this.$scope.componentInstancesConstraints[this.$scope.currentComponent.selectedInstance.uniqueId].properties : - []; - } - }); - this.$scope.$watch('componentInstancesConstraints', (constraints: Array):void => { - if (angular.isDefined(constraints)) { - if(this.$scope.isComponentInstanceSelected()) { - this.$scope.selectedInstanceConstraints = this.$scope.componentInstancesConstraints[this.$scope.currentComponent.selectedInstance.uniqueId] ? - this.$scope.componentInstancesConstraints[this.$scope.currentComponent.selectedInstance.uniqueId].properties || [] : - []; - } - } - }); - - this.$scope.updateSelectedInstanceConstraints = (constraintsList:Array):void => { - this.$scope.componentInstancesConstraints[this.$scope.currentComponent.selectedInstance.uniqueId].properties = constraintsList; - this.$scope.selectedInstanceConstraints = this.$scope.componentInstancesConstraints[this.$scope.currentComponent.selectedInstance.uniqueId].properties; - } - - this.$scope.loadConstraints = ():void => { - this.loadConstraints(); - } - - this.$scope.registerCreateInstanceEvent(() => { - this.initInstancesWithProperties(); - }); - - this.$scope.registerChangeComponentInstanceNameEvent((updatedComponentInstance) => { - this.$scope.currentComponent.selectedInstance = updatedComponentInstance; - }); - - this.$scope.$on('$destroy', this.$scope.unregisterCreateInstanceEvent); - this.$scope.$on('$destroy', this.$scope.unregisterChangeComponentInstanceNameEvent); - } - - private loadConstraints = ():void => { - this.ComponentServiceNg2.getServiceFilterConstraints(this.$scope.service).subscribe((response) => { - this.$scope.componentInstancesConstraints = response.nodeFilterData; - }); - } - - public notifyDependencyEventsObserver = (isChecked: boolean):void => { - this.eventListenerService.notifyObservers(DEPENDENCY_EVENTS.ON_DEPENDENCY_CHANGE, isChecked); - } -} \ No newline at end of file diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/service-dependencies/service-dependencies-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/service-dependencies/service-dependencies-view.html deleted file mode 100644 index ba50994529..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/service-dependencies/service-dependencies-view.html +++ /dev/null @@ -1,25 +0,0 @@ - - -
    - - Service Dependencies -
    -
    -
    -
    - - -
    -
    -
    -
    \ No newline at end of file diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/structure/structure-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/structure/structure-view.html deleted file mode 100644 index 4d89625e67..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/structure/structure-view.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - -
    - - Composition -
    -
    - -
    - -
    -
    -
    diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/structure/structure-view.ts b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/structure/structure-view.ts deleted file mode 100644 index 41f24dc8e8..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/structure/structure-view.ts +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {ICompositionViewModelScope} from "../../composition-view-model"; - -interface IStructureViewModel extends ICompositionViewModelScope { -} - -export class StructureViewModel { - static '$inject' = [ - '$scope' - ]; - - constructor(private $scope:IStructureViewModel) { - } -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-description-popover.html b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-description-popover.html deleted file mode 100644 index 94c28a0796..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-description-popover.html +++ /dev/null @@ -1,39 +0,0 @@ - - - -
    - -
    - - -
    - - - -
    -
    -
    diff --git a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts deleted file mode 100644 index fc3de6e9e1..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts +++ /dev/null @@ -1,352 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -//@require "./*.html" -'use strict'; -import * as _ from "lodash"; -import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model"; -import {ArtifactModel, ArtifactGroupModel, Resource} from "app/models"; -import {ArtifactsUtils, ModalsHandler, ValidationUtils} from "app/utils"; -import {ComponentServiceNg2} from "app/ng2/services/component-services/component.service"; -import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response"; -import {GenericArtifactBrowserComponent} from "../../../../ng2/components/logic/generic-artifact-browser/generic-artifact-browser.component"; -import {PathsAndNamesDefinition} from "../../../../models/paths-and-names"; -import {ModalService as ModalServiceSdcUI} from "sdc-ui/lib/angular/modals/modal.service"; -import {IModalConfig} from "sdc-ui/lib/angular/modals/models/modal-config"; -import {CacheService} from "../../../../services/cache-service"; -import {GabConfig} from "../../../../models/gab-config"; - -interface IDeploymentArtifactsViewModelScope extends IWorkspaceViewModelScope { - tableHeadersList:Array; - reverse:boolean; - sortBy:string; - artifacts:Array; - editForm:ng.IFormController; - isLoading:boolean; - artifactDescriptions:any; - selectedArtifactId:string; - popoverTemplate:string; - - addOrUpdate(artifact:ArtifactModel):void; - updateSelectedArtifact():void; - delete(artifact:ArtifactModel):void; - sort(sortBy:string):void; - noArtifactsToShow():boolean; - getValidationPattern(validationType:string, parameterType?:string):RegExp; - validateJson(json:string):boolean; - resetValue(parameter:any):void; - viewModeOrCsarComponent():boolean; - isLicenseArtifact(artifact:ArtifactModel):void; - getEnvArtifact(heatArtifact:ArtifactModel):ArtifactModel; - getEnvArtifactName(artifact:ArtifactModel):string; - openEditEnvParametersModal(artifact:ArtifactModel):void; - openDescriptionPopover(artifactId:string):void; - closeDescriptionPopover():void; -} - -export class DeploymentArtifactsViewModel { - - static '$inject' = [ - '$scope', - '$templateCache', - '$filter', - 'Sdc.Services.CacheService', - 'ValidationUtils', - 'ArtifactsUtils', - 'ModalsHandler', - 'ComponentServiceNg2', - 'ModalServiceSdcUI' - ]; - - constructor(private $scope:IDeploymentArtifactsViewModelScope, - private $templateCache:ng.ITemplateCacheService, - private $filter:ng.IFilterService, - private cacheService:CacheService, - private validationUtils:ValidationUtils, - private artifactsUtils:ArtifactsUtils, - private ModalsHandler:ModalsHandler, - private ComponentServiceNg2: ComponentServiceNg2, - private ModalServiceSdcUI: ModalServiceSdcUI) { - this.initScope(); - } - - private initDescriptions = ():void => { - this.$scope.artifactDescriptions = {}; - _.forEach(this.$scope.component.deploymentArtifacts, (artifact:ArtifactModel):void => { - this.$scope.artifactDescriptions[artifact.artifactLabel] = artifact.description; - }); - }; - - private setArtifact = (artifact:ArtifactModel):void => { - if (!artifact.description || !this.$scope.getValidationPattern('string').test(artifact.description)) { - artifact.description = this.$scope.artifactDescriptions[artifact.artifactLabel]; - } - }; - - private initScopeArtifacts = ()=> { - this.$scope.artifacts = _.values(this.$scope.component.deploymentArtifacts); - _.forEach(this.$scope.artifacts, (artifact:ArtifactModel):void => { - artifact.envArtifact = this.getEnvArtifact(artifact); - }); - }; - - private initArtifacts = (loadFromServer:boolean):void => { - if (loadFromServer) { - this.$scope.isLoading = true; - this.ComponentServiceNg2.getComponentDeploymentArtifacts(this.$scope.component).subscribe((response:ComponentGenericResponse) => { - this.$scope.component.deploymentArtifacts = response.deploymentArtifacts; - this.initScopeArtifacts(); - this.$scope.isLoading = false; - }); - } else { - this.initScopeArtifacts(); - } - - }; - - private getEnvArtifact = (heatArtifact:ArtifactModel):ArtifactModel=> { - return _.find(this.$scope.artifacts, (item:ArtifactModel)=> { - return item.generatedFromId === heatArtifact.uniqueId; - }); - }; - - private getCurrentArtifact = ():ArtifactModel => { - if (!this.$scope.selectedArtifactId) { - return null; - } - let artifact:ArtifactModel = this.$scope.artifacts.filter((art) => { - return art.uniqueId == this.$scope.selectedArtifactId; - })[0]; - return artifact; - } - - private initScope = ():void => { - let self = this; - this.$scope.isLoading = false; - this.$scope.selectedArtifactId = null; - this.initDescriptions(); - if(this.$scope.component.deploymentArtifacts) { - this.initArtifacts(false); - } else { - this.initArtifacts(true); - } - this.$scope.setValidState(true); - - this.$scope.tableHeadersList = [ - {title: 'Name', property: 'artifactDisplayName'}, - {title: 'Type', property: 'artifactType'}, - {title: 'Deployment timeout', property: 'timeout'}, - {title: 'Version', property: 'artifactVersion'}, - {title: 'UUID', property: 'artifactUUID'} - ]; - - this.$templateCache.put("deployment-artifacts-description-popover.html", require('app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-description-popover.html')); - this.$scope.popoverTemplate = "deployment-artifacts-description-popover.html"; - - this.$scope.isLicenseArtifact = (artifact:ArtifactModel):boolean => { - let isLicense:boolean = false; - if (this.$scope.component.isResource() && (this.$scope.component).isCsarComponent()) { - - isLicense = this.artifactsUtils.isLicenseType(artifact.artifactType); - } - - return isLicense; - }; - - this.$scope.sort = (sortBy:string):void => { - this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false; - this.$scope.sortBy = sortBy; - }; - - this.$scope.getValidationPattern = (validationType:string, parameterType?:string):RegExp => { - return this.validationUtils.getValidationPattern(validationType, parameterType); - }; - - this.$scope.validateJson = (json:string):boolean => { - if (!json) { - return true; - } - return this.validationUtils.validateJson(json); - }; - - this.$scope.viewModeOrCsarComponent = ():boolean => { - return this.$scope.isViewMode() || (this.$scope.component.isResource() && (this.$scope.component).isCsarComponent()); - }; - - this.$scope.addOrUpdate = (artifact:ArtifactModel):void => { - artifact.artifactGroupType = 'DEPLOYMENT'; - let artifactCopy = new ArtifactModel(artifact); - - let success = (response:any):void => { - this.$scope.artifactDescriptions[artifactCopy.artifactLabel] = artifactCopy.description; - this.initArtifacts(true); - // this.$scope.artifacts = _.values(this.$scope.component.deploymentArtifacts); - }; - - let error = (err:any):void => { - console.log(err); - this.initArtifacts(true); - // self.$scope.artifacts = _.values(self.$scope.component.deploymentArtifacts); - }; - - this.ModalsHandler.openArtifactModal(artifactCopy, this.$scope.component).then(success, error); - }; - - this.$scope.noArtifactsToShow = ():boolean => { - return !_.some(this.$scope.artifacts, 'esId'); - }; - - this.$scope.resetValue = (parameter:any):void => { - if (!parameter.currentValue && parameter.defaultValue) { - parameter.currentValue = parameter.defaultValue; - } - else if ('boolean' == parameter.type) { - parameter.currentValue = parameter.currentValue.toUpperCase(); - } - }; - - this.$scope.$watch('editForm.$valid', ():void => { - if (this.$scope.editForm) { - // this.$scope.setValidState(this.$scope.editForm.$valid); - } - }); - - this.$scope.updateSelectedArtifact = ():void => { - if (!this.$scope.isViewMode() && !this.$scope.isLoading) { - let artifact:ArtifactModel = this.getCurrentArtifact(); - this.setArtifact(artifact); //resets artifact description to original value if invalid. - if (artifact && artifact.originalDescription != artifact.description) { - this.$scope.isLoading = true; - let onSuccess = (responseArtifact:ArtifactModel):void => { - this.$scope.artifactDescriptions[responseArtifact.artifactLabel] = responseArtifact.description; - // this.$scope.artifacts = _.values(this.$scope.component.deploymentArtifacts); - this.initArtifacts(true); - this.$scope.isLoading = false; - }; - - let onFailed = (error:any):void => { - console.log('Delete artifact returned error:', error); - this.$scope.isLoading = false; - }; - - this.$scope.component.addOrUpdateArtifact(artifact).then(onSuccess, onFailed); - } - } - }; - - this.$scope.delete = (artifact:ArtifactModel):void => { - let onOk = ():void => { - this.$scope.isLoading = true; - let onSuccess = ():void => { - this.$scope.isLoading = false; - this.initArtifacts(true); - //this.$scope.artifacts = _.values(this.$scope.component.deploymentArtifacts); - }; - - let onFailed = (error:any):void => { - this.$scope.isLoading = false; - console.log('Delete artifact returned error:', error); - }; - - this.$scope.component.deleteArtifact(artifact.uniqueId, artifact.artifactLabel).then(onSuccess, onFailed); - }; - - let title:string = self.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TITLE"); - let message:string = self.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TEXT", "{'name': '" + artifact.artifactDisplayName + "'}"); - this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk); - }; - - this.$scope.getEnvArtifactName = (artifact:ArtifactModel):string => { - let envArtifact = this.$scope.getEnvArtifact(artifact); - if (envArtifact) { - return envArtifact.artifactDisplayName; - } - }; - - this.$scope.openGenericArtifactBrowserModal = (artifact:ArtifactModel):void => { - let self = this; - const title = 'Generic Artifact Browser'; - let modalConfig: IModalConfig = { - size: 'xl', - title: title, - type: 'custom', - buttons: [{ - id: 'closeGABButton', - text: 'Close', - size: "'x-small'", - closeModal: true - }] - }; - - const uiConfiguration: any = this.cacheService.get('UIConfiguration'); - let noConfig: boolean = false; - let pathsandnames: PathsAndNamesDefinition[] = []; - - if(typeof uiConfiguration.gab === 'undefined') { - noConfig = true; - } else { - const gabConfig: GabConfig = uiConfiguration.gab - .find(config => config.artifactType === artifact.artifactType); - if(typeof gabConfig === 'undefined') { - noConfig = true; - } else { - pathsandnames = gabConfig.pathsAndNamesDefinitions; - } - } - - if(noConfig) { - const msg = self.$filter('translate')("DEPLOYMENT_ARTIFACT_GAB_NO_CONFIG"); - this.ModalServiceSdcUI.openAlertModal(title, msg); - } - - const modalInputs = { - pathsandnames: pathsandnames, - artifactid: artifact.esId, - resourceid: this.$scope.component.uniqueId - }; - - this.ModalServiceSdcUI.openCustomModal(modalConfig, GenericArtifactBrowserComponent, modalInputs); - }; - - this.$scope.openEditEnvParametersModal = (artifact:ArtifactModel):void => { - this.ModalsHandler.openEditEnvParametersModal(artifact, this.$scope.component).then(()=> { - this.initArtifacts(true); - }, ()=> { - this.initArtifacts(true); - }); - }; - - this.$scope.openDescriptionPopover = (artifactId:string):void => { - if (this.$scope.selectedArtifactId && this.$scope.selectedArtifactId != artifactId) { - this.$scope.updateSelectedArtifact(); - } - this.$scope.selectedArtifactId = artifactId; - - }; - - this.$scope.closeDescriptionPopover = ():void => { - if (this.$scope.selectedArtifactId) { - this.$scope.updateSelectedArtifact(); - this.$scope.selectedArtifactId = null; - } - }; - }; -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view.html b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view.html deleted file mode 100644 index a26bcdeccd..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view.html +++ /dev/null @@ -1,147 +0,0 @@ - - -
    - -
    Add
    - -
    - -
    - -
    -
    {{header.title}} - -
    -
    -
    - -
    - - - - -
    -
    -
    -
    - -
    - {{artifact.artifactDisplayName}} - - -
    - -
    - {{artifact.artifactType}} -
    -
    - {{artifact.timeout? artifact.timeout:''}} -
    -
    - {{artifact.artifactVersion}} -
    -
    - {{artifact.artifactUUID}} -
    - -
    - - - - - -
    -
    -
    - -
    - {{artifact.envArtifact.artifactDisplayName}} -
    - -
    - {{artifact.envArtifact.artifactType}} -
    -
    - {{artifact.envArtifact.timeout? artifact.envArtifact.timeout:''}} -
    -
    - {{artifact.envArtifact.artifactVersion}} -
    -
    - {{artifact.envArtifact.artifactUUID}} -
    - - -
    - - - -
    -
    - - - - - - - - - - - - - - - - - - - - - - - -
    -
    -
    -
    -
    diff --git a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts.less b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts.less deleted file mode 100644 index f67d088b5a..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts.less +++ /dev/null @@ -1,201 +0,0 @@ -.workspace-deployment-artifact { - width: 93%; - display: inline-block; - .table-container-flex .table .body .data-row + div.item-opened { - align-items: center; - padding: 10px 40px 10px 30px; - } - - .w-sdc-classic-btn { - float: right; - margin-bottom: 10px; - } - - - .heat-env-connect-container{ - background-color: white; - position: absolute; - height: 70px; - width:20px; - left: 0; - top:0; - } - .heat-env-connect-container-view-mode{ - background-color: @tlv_color_t; - } - .heat-env-connect{ - border-left: 1px #848586 solid; - height: 50px; - margin-left: 10px; - margin-top: 10px; - border-top: 1px #848586 solid; - border-bottom: 1px #848586 solid; - width: 11px; - float: left; - - } - - .artifact-name{ - width:85%; - } - - .table-container-flex .table .body .data-row div .heat-env-connect-container{ - border-right: none; - } - - .i-sdc-designer-sidebar-section-content-item-file-link::before{ - content:""; - background-color: white; - width: 12px; - - } - - - - .table { - height:490px; - margin-bottom: 0; - } - - .parameter-description { - .circle(18px, @color_p); - content: '?'; - line-height: 18px; - vertical-align: middle; - margin-left: 5px; - cursor: default; - display: inline-block; - position: absolute; - top: 16px; - } - - .table-container-flex { - - margin-top: 0; - - .text{ - overflow: hidden; - text-overflow: ellipsis; - display: inline-block; - white-space: nowrap; - } - - .flex-item:nth-child(1) { - flex-grow: 15; - .hand; - padding-left: 30px; - position: relative; - span.table-arrow { - margin-right: 7px; - } - .description-popover-icon{ - float:right; - margin-top:6px; - } - } - - .flex-item:nth-child(2) { - flex-grow: 6; - } - - .flex-item:nth-child(3) { - flex-grow: 9; - } - - .flex-item:nth-child(4) { - flex-grow: 3; - } - - .flex-item:nth-child(5) { - flex-grow: 20; - } - - .flex-item:nth-child(6) { - flex-grow: 5; - - &.table-btn-col { - display: flex; - justify-content: space-between; - align-items: center; - - button { - flex: 0 1 auto; - background-color: transparent; - border: 0; - margin: 0; - } - .edit-paramtes-button { - order: -1; - } - } - } - } - .w-sdc-form{ - text-align: left; - - .w-sdc-env-params{ - border-top: 1px solid #cdcdcd; - margin: 25px 0 10px 0; - } - - .i-sdc-form-textarea { - border: 1px solid @color_e; - min-height: 60px; - padding: 10px 13px; - width: 100%; - resize: none; - - } - - .w-sdc-form-item { - &.error { - .i-sdc-form-input, - .i-sdc-form-select, - .i-sdc-form-textarea { - border-color: @color_h; - outline: none; - box-sizing: border-box; - } - } - } - - .i-sdc-env-form-label{ - font-family: @font-opensans-medium; - color: @main_color_m; - overflow: hidden; - max-width: 450px; - text-overflow: ellipsis; - display: inline-block; - white-space: nowrap; - margin-top: 14px; - - &.required::before { - color: #f33; - content: '*'; - margin-right: 4px; - } - } - } -} - -.table-container-flex .table .body .scrollbar-container { - overflow-x:auto !important; //need to override the overflow-hidden for the table so that the popover auto positioning works - min-height: 400px; -} - -.parameter-description-popover.deployment-artifact-view { - margin-left: -22px; - z-index: 1040; - min-width: 300px; - .input-error { - .q_12_m; - } - .error textarea{ - border-color: @main_color_g; - color: @color_h; - outline: none; - } - .popover-content textarea { - width:100%; - } -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view-model.ts deleted file mode 100644 index 9df377c5fc..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view-model.ts +++ /dev/null @@ -1,146 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model"; -import {ComponentFactory, MenuHandler, ChangeLifecycleStateHandler, ModalsHandler} from "app/utils"; -import {LeftPaletteLoaderService, CacheService, SharingService} from "app/services"; -import {Component, IAppMenu, Tab, ComponentInstance} from "app/models"; -import {GRAPH_EVENTS} from "../../../../utils/constants"; -import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response"; -import {EventListenerService} from "../../../../services/event-listener-service"; -import {ComponentServiceNg2} from "../../../../ng2/services/component-services/component.service"; - -export interface IDeploymentViewModelScope extends IWorkspaceViewModelScope { - - currentComponent:Component; - selectedComponent:Component; - isLoading:boolean; - sharingService:SharingService; - sdcMenu:IAppMenu; - version:string; - isViewOnly:boolean; - tabs:Array; - selectedTab: Tab; - isComponentInstanceSelected():boolean; - updateSelectedComponent():void - openUpdateModal(); - deleteSelectedComponentInstance():void; - onBackgroundClick():void; - setSelectedInstance(componentInstance:ComponentInstance):void; - printScreen():void; - -} - -export class DeploymentViewModel { - - static '$inject' = [ - '$scope', - '$templateCache', - 'sdcMenu', - 'MenuHandler', - '$state', - 'Sdc.Services.SharingService', - '$filter', - 'Sdc.Services.CacheService', - 'ComponentFactory', - 'ChangeLifecycleStateHandler', - 'LeftPaletteLoaderService', - 'ModalsHandler', - 'EventListenerService', - 'ComponentServiceNg2' - ]; - - constructor(private $scope:IDeploymentViewModelScope, - private $templateCache:ng.ITemplateCacheService, - private sdcMenu:IAppMenu, - private MenuHandler:MenuHandler, - private $state:ng.ui.IStateService, - private sharingService:SharingService, - private $filter:ng.IFilterService, - private cacheService:CacheService, - private ComponentFactory:ComponentFactory, - private ChangeLifecycleStateHandler:ChangeLifecycleStateHandler, - private LeftPaletteLoaderService:LeftPaletteLoaderService, - private ModalsHandler:ModalsHandler, - private eventListenerService: EventListenerService, - private ComponentServiceNg2: ComponentServiceNg2) { - - this.$scope.setValidState(true); - this.initScope(); - this.initGraphData(); - } - - - private initComponent = ():void => { - - this.$scope.currentComponent = this.$scope.component; - this.$scope.selectedComponent = this.$scope.currentComponent; - this.updateUuidMap(); - this.$scope.isViewOnly = this.$scope.isViewMode(); - }; - - - private updateUuidMap = ():void => { - /** - * In case user press F5, the page is refreshed and this.sharingService.currentEntity will be undefined, - * but after loadService or loadResource this.sharingService.currentEntity will be defined. - * Need to update the uuidMap with the new resource or service. - */ - this.sharingService.addUuidValue(this.$scope.currentComponent.uniqueId, this.$scope.currentComponent.uuid); - }; - - private initRightTabs = ()=> { - if (this.$scope.currentComponent.modules) { - this.$templateCache.put("hierarchy-view.html", require('app/view-models/tabs/hierarchy/hierarchy-view.html')); - let hierarchyTab = new Tab("hierarchy-view.html", 'Sdc.ViewModels.HierarchyViewModel', 'hierarchy', this.$scope.isViewMode(), this.$scope.currentComponent, 'hierarchy'); - this.$scope.tabs.push(hierarchyTab) - } - } - - private initGraphData = ():void => { - if(!this.$scope.component.componentInstances || !this.$scope.component.componentInstancesRelations || !this.$scope.component.modules) { - this.ComponentServiceNg2.getDeploymentGraphData(this.$scope.component).subscribe((response:ComponentGenericResponse) => { - this.$scope.component.componentInstances = response.componentInstances; - this.$scope.component.componentInstancesRelations = response.componentInstancesRelations; - this.$scope.component.modules = response.modules; - this.$scope.isLoading = false; - this.initComponent(); - this.initRightTabs(); - this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_DEPLOYMENT_GRAPH_DATA_LOADED); - this.$scope.selectedTab = this.$scope.tabs[0]; - }); - } else { - this.$scope.isLoading = false; - this.initRightTabs(); - this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_DEPLOYMENT_GRAPH_DATA_LOADED); - - } - }; - - private initScope = ():void => { - this.$scope.isLoading = true; - this.$scope.sharingService = this.sharingService; - this.$scope.sdcMenu = this.sdcMenu; - this.$scope.version = this.cacheService.get('version'); - this.initComponent(); - this.$scope.tabs = Array(); - } -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view.html b/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view.html deleted file mode 100644 index aae03135a3..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view.html +++ /dev/null @@ -1,26 +0,0 @@ - - -
    - -
    - -
    - -
    - -
    -
    diff --git a/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment.less b/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment.less deleted file mode 100644 index f51ff6220d..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment.less +++ /dev/null @@ -1,34 +0,0 @@ -.deployment-view { - - display: inline-block; - text-align: left; - align-items: left; - padding: 0; - width: 100%; - height: 100%; - - .w-sdc-deployment-canvas { - .noselect; - .bg_c; - position: relative; - bottom: 0; - width: 100%; - height: 100%; - z-index: 0; - - .view-mode{ - background-color: #f8f8f8; - border:0; - } - } - - .w-sdc-deployment-right-bar { - - .noselect; - bottom: 0; - position: absolute; - right: 0px; - transition: right 0.2s; - top: @action_nav_height; - } -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model.ts deleted file mode 100644 index eab06f28e8..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model.ts +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import * as _ from "lodash"; -import {Distribution, DistributionComponent, ExportExcel} from "app/models"; - -interface IDistributionStatusModalViewModelScope { - distribution:Distribution; - status:string; - getStatusCount(distributionComponent:Array):any; - getUrlName(url:string):string; - modalDitributionStatus:ng.ui.bootstrap.IModalServiceInstance; - footerButtons:Array; - //exportExcelData:ExportExcel; - close():void; - initDataForExportExcel():ExportExcel; -} - -export class DistributionStatusModalViewModel { - - static '$inject' = ['$scope', '$uibModalInstance', 'data', '$filter']; - - constructor(private $scope:IDistributionStatusModalViewModelScope, - private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance, - private data:any, - private $filter:ng.IFilterService) { - this.initScope(); - } - - private generateMetaDataForExportExcel = ():Array=> { - let metaData = []; - metaData[0] = 'Name:' + this.data.component.name + '| UUID:' + this.data.component.uuid + '| Invariant UUID:' + this.data.component.invariantUUID; - metaData[1] = 'Distribution ID:' + this.$scope.distribution.distributionID + - '| USER ID:' + this.$scope.distribution.userId + - '| Time[UTC]:' + this.$filter('date')(this.$scope.distribution.timestamp, 'MM/dd/yyyy h:mma', 'UTC') + - '| Status:' + this.$scope.distribution.deployementStatus; - return metaData; - }; - - private generateDataObjectForExportExcel = ():any=> { - let correctFormatDataObj = []; - _.each(this.$scope.distribution.distributionComponents, (dComponent:DistributionComponent) => { - if (dComponent.status == this.$scope.status) { - correctFormatDataObj.push({ - 'omfComponentID': dComponent.omfComponentID, - 'artiFactName': this.$scope.getUrlName(dComponent.url), - 'url': dComponent.url, - 'timestamp': this.$filter('date')(dComponent.timestamp, 'MM/dd/yyyy h:mma', 'UTC'), - 'status': dComponent.status - }); - } - }); - return correctFormatDataObj; - }; - - private initScope = ():void => { - this.$scope.distribution = this.data.distribution; - this.$scope.status = this.data.status; - this.$scope.modalDitributionStatus = this.$uibModalInstance; - - - this.$scope.getUrlName = (url:string):string => { - let urlName:string = _.last(url.split('/')); - return urlName; - }; - - this.$scope.initDataForExportExcel = ():ExportExcel => { - let exportExcelData = new ExportExcel(); - exportExcelData.fileName = this.$scope.status; - exportExcelData.groupByField = "omfComponentID"; - exportExcelData.tableHeaders = ["Component ID", "Artifact Name", "URL", "Time(UTC)", "Status"]; - exportExcelData.metaData = this.generateMetaDataForExportExcel(); - exportExcelData.dataObj = this.generateDataObjectForExportExcel(); - return exportExcelData; - }; - - this.$scope.close = ():void => { - this.$uibModalInstance.close(); - }; - - this.$scope.footerButtons = [ - {'name': 'Close', 'css': 'blue', 'callback': this.$scope.close} - ]; - - }; -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view.html b/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view.html deleted file mode 100644 index 0e58959e9a..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view.html +++ /dev/null @@ -1,146 +0,0 @@ - - - - -
    -
    - -
    - -
    - - -
    - - -
    -
      -
    • -
      - -
      -
      -
      -
      Distribution ID
      -
      -
      -
      -
      -
      -
      -
      -
      Time[UTC]:
      -
      -
      -
      - - -
      -
      -
      -
      Status: {{status}}
      - -
      -
      -
      - -
        -
      • -
        -
        -
        -
        {{omfComponentID}} {{omfComponentList.length}} -
        -
        -
        -
        -
        -
        -
        -
        Component ID
        -
        Artifact Name
        -
        URL
        -
        Time(UTC)
        -
        Status
        -
        - -
        -
        -
        - {{urlList[0].omfComponentID}} -
        -
        - {{getUrlName(urlList[0].url)}} -
        -
        -
        {{urlList[0].url}}
        - -
        -
        -
        -
        {{urlList[0].status}}
        -
        - - -
        -
        -
          -
        • - - {{distributionComponent.status}} - Reason: Component has determined artifact is not needed. - Reason: {{distributionComponent.errorReason}} -
        • -
        -
        -
        -
        -
        -
        -
      • -
      -
    • -
    -
    - -
    -
    - - -
    diff --git a/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal.less b/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal.less deleted file mode 100644 index d167083a2b..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal.less +++ /dev/null @@ -1,40 +0,0 @@ -.w-sdc-classic-top-line-modal { - - .w-sdc-modal-head { - // border-bottom: none; - } - .w-sdc-distribution-view { - .actions-buttons { - height: 29px; - padding: 0 25px 0 0px; - span{ - float: right; - } - } - - .w-sdc-distribution-view-content { - height: 500px; - } - - .w-sdc-distribution-view-content-section { - - .w-sdc-distribute-parent-block { - .w-sdc-distribute-components-block { - - .omf-component-row { - .w-sdc-distribute-status-block { - margin-left: 0; - } - - } - div { - padding-left: 0; - } - } - - } - - } - } -} - diff --git a/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view-model.ts deleted file mode 100644 index 47ec1fd9e3..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view-model.ts +++ /dev/null @@ -1,131 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import * as _ from "lodash"; -import {Distribution, DistributionComponent, Service} from "app/models"; -import {ModalsHandler, Dictionary} from "app/utils"; -import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model"; - -interface IDistributionViewModel extends IWorkspaceViewModelScope { - modalDistribution:ng.ui.bootstrap.IModalServiceInstance; - service:Service; - distributions:Array; - showComponents(distribution:Distribution):void; - markAsDeployed(distribution:Distribution):void; - getStatusCount(distributionComponent:Array):any; - initDistributions():void; - getUrlName(url:string):string; - close():void; - openDisributionStatusModal:Function; -} - -export class DistributionViewModel { - - static '$inject' = [ - '$scope', - 'ModalsHandler' - - ]; - - constructor(private $scope:IDistributionViewModel, - private ModalsHandler:ModalsHandler) { - this.initScope(); - this.$scope.setValidState(true); - } - - private initScope = ():void => { - this.$scope.service = this.$scope.component; - - - // Open Distribution status modal - this.$scope.openDisributionStatusModal = (distribution:Distribution, status:string):void => { - this.ModalsHandler.openDistributionStatusModal(distribution, status, this.$scope.component).then(()=> { - // OK - }, ()=> { - // ERROR - }); - }; - - - this.$scope.showComponents = (distribution:Distribution):void => { - let onError = (response) => { - console.info('onError showComponents', response); - }; - let onSuccess = (distributionComponents:Array) => { - distribution.distributionComponents = distributionComponents; - distribution.statusCount = this.$scope.getStatusCount(distribution.distributionComponents); - // distribution.components = this.aggregateDistributionComponent(distributionComponents);; - }; - this.$scope.service.getDistributionsComponent(distribution.distributionID).then(onSuccess, onError); - }; - - this.$scope.getStatusCount = (distributionComponent:Array):any => { - return _.countBy(distributionComponent, 'status') - }; - - this.$scope.getUrlName = (url:string):string => { - let urlName:string = _.last(url.split('/')); - return urlName; - }; - - this.$scope.markAsDeployed = (distribution:Distribution):void => { - let onError = (response) => { - console.info('onError markAsDeployed', response); - }; - let onSuccess = (result:any) => { - distribution.deployementStatus = 'Deployed'; - }; - this.$scope.service.markAsDeployed(distribution.distributionID).then(onSuccess, onError); - - }; - - this.$scope.initDistributions = ():void => { - let onError = (response) => { - console.info('onError initDistributions', response); - }; - let onSuccess = (distributions:Array) => { - this.$scope.distributions = distributions; - }; - this.$scope.service.getDistributionsList().then(onSuccess, onError); - }; - - this.$scope.initDistributions(); - - }; - - - private aggregateDistributionComponent = (distributionComponents:Array):any => { - let aggregateDistributions:Dictionary>> = new Dictionary>>(); - let tempAggregateDistributions:any = _.groupBy(distributionComponents, 'omfComponentID'); - let aa = new Dictionary>(); - - let tempAggregate:any; - _.forEach(tempAggregateDistributions, (distributionComponents:Array, omfComponentID:string)=> { - - let urls:any = _.groupBy(distributionComponents, 'url'); - aggregateDistributions.setValue(omfComponentID, urls); - // aggregateDistributions[omfComponentID] = ; - - }); - console.log(aggregateDistributions); - return aggregateDistributions; - }; -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view.html b/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view.html deleted file mode 100644 index babe5c2e5a..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view.html +++ /dev/null @@ -1,198 +0,0 @@ - - -
    -
    -
    DISTRIBUTION
    -
    - -
    -
    - - - -
    -
      -
    • -
      -
      -
      -
      -
      -
      Distribution ID
      -
      -
      -
      -
      -
      -
      -
      -
      Time[UTC]:
      -
      -
      -
      - - -
      -
      -
      -
      -
      -
      -
      Total Artifacts:
      -
      Notified:
      - - - - - -
      Deploy Errors:
      -
      Download Errors:
      -
      -
      -
      - -
        - -
      • -
        -
        -
        -
        {{omfComponentID}} {{(statusCount.NOT_NOTIFIED || 0) + (statusCount.NOTIFIED || 0) }} -
        -
        Notified:
        -
        Downloaded:
        -
        Deployed:
        -
        Not Notified:
        -
        Deploy Errors:
        -
        Download Errors:
        -
        -
        -
        -
        -
        -
        -
        Component ID
        -
        Artifact Name
        -
        URL
        -
        Time(UTC)
        -
        Status
        -
        - -
        -
        -
        - {{urlList[0].omfComponentID}} -
        -
        - {{urlList[0].displayUrl}} -
        -
        -
        {{urlList[0].url}}
        - -
        -
        -
        -
        - {{urlList[0].status}} -
        -
        - - -
        -
        -
          -
        • - - {{distributionComponent.status}} - Reason: Component has determined artifact is not needed. - Reason: {{distributionComponent.errorReason}} -
        • -
        -
        -
        -
        -
        -
        -
      • -
      -
    • -
    -
    - -
    -
    diff --git a/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution.less b/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution.less deleted file mode 100644 index ee1f7ed2d6..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution.less +++ /dev/null @@ -1,362 +0,0 @@ - -.w-sdc-distribution-view { - text-align: left; - - .g_1; - min-height: 500px; - - .w-sdc-distribution-view-distributed-green-text { - .l_9; - .bold; - } - .w-sdc-distribution-view-distributed-error-red-text { - .h_9; - .bold; - } - - .bg_c; - vertical-align: top; - padding: 30px 10px; - width: 100%; - - .w-sdc-distribution-view-header { - display: flex; - -webkit-justify-content: space-between; - margin: 0 25px 5px 40px; - - .header-spacer { - flex-grow: 5; - } - } - - .top-search { - position: relative; - input { - &.search-text { - height: 26px; - line-height: 26px; - margin: 0 18px 4px 20px; - padding-right: 25px; - } - - } - .magnification { - top: 8px; - right: 25px; - } - } - - .w-sdc-distribution-view-content { - .perfect-scrollbar; - padding: 0 25px 0 0px; - margin-bottom: 25px; - height: 700px; - overflow: hidden; - position: relative; - - } - - .w-sdc-distribution-view-title { - .s_14_r; - - line-height: 30px; - - span { - padding-left: 5px; - } - } - - .blue-font { - .a_14_m; - - } - - .red-font { - .q_14_m; - } - - .w-sdc-distribution-view-block { - div { - display: inline-block; - } - } - - .w-sdc-distribution-view-content-section { - ul { - list-style-type: none; - } - - .distribution-bth { - .hand; - &.disabled { - cursor: none; - } - } - - .copy-link { - padding-right: 19px; - margin-left: 8px; - cursor: pointer; - - } - - .w-sdc-distribute-row-extends { - border-Left: solid 4px transparent; - &.extends { - border-left: solid 4px @main_color_c; - border-bottom: 1px solid @border_color_f; - margin-bottom: 10px; - } - } - .w-sdc-distribute-parent-block { - border: 1px solid @main_color_o;; - width: 100%; - margin-bottom: 6px; - - .status-icon { - vertical-align: middle; - margin-bottom: 4px; - } - - &.extends { - background-color: @tlv_color_t; - } - - :not(.disable-hover):hover { - background-color: @tlv_color_u; - } - - .title-section { - display: inline-block; - margin-right: 10px; - flex-basis: 0; - } - - .title { - .l_12_m; - font-weight: bold; - } - .w-sdc-distribute-content { - display: flex; - align-items: center; - justify-content: space-between; - margin-left: 10px; - } - - .w-sdc-distribution-arrow-btn { - .sprite-new; - .arrow-up-small; - margin: 0 6px; - display: inline-table; - } - .extends.w-sdc-distribution-arrow-btn { - -webkit-transform: rotate(180deg); - -ms-transform: rotate(180deg); - transform: rotate(180deg); - } - - .w-sdc-distribute-row { - display: flex; - align-items: center; - justify-content: space-between; - - .w-sdc-distribute-row-content { - margin: 15px 31px 10px 0; - width: 100%; - .w-sdc-distribute-status-block { - border-top: solid 1px @main_color_o; - } - .item-1 { - flex-grow: 2; - } - .item-2 { - flex-grow: 1; - } - .item-3 { - flex-grow: 1; - } - .item-4 { - flex-grow: 1; - } - .item-5 { - flex-grow: 1; - } - } - } - - .w-sdc-distribute-status-block { - display: flex; - align-items: center; - justify-content: space-between; - margin: 10px 5px 0 5px; - padding: 5px 5px 0 5px;; - width: 100%; - div { - border-left: 1px solid @main_color_o; - padding: 0 12px; - } - - .link { - .a_14_m; - cursor: pointer; - &:hover{ - text-decoration: underline; - .b_14_m; - } - } - - span { - padding: 2px; - } - - .deployed { - margin-left: 10px; - .sprite-new; - .success-circle-small; - } - - .error { - .q_14_m; - margin-left: 10px; - .sprite-new; - .error-icon; - } - - .status-item-1 { - border-left: 0; - } - - .status-item-6 { - flex-grow: 1; - border-left: none; - text-align: right; - } - } - - .w-sdc-distribute-components-block { - padding: 0; - padding-bottom: 5px; - list-style-type: none; - - li { - margin: 5px 2px; - } - - .omf-component-row { - border: 1px solid @border_color_f; - padding-left: 3px; - background-color: white; - margin: 0 30px; - &.extends { - padding-left: 0; - border-Left: solid 4px @main_color_c; - - } - - .w-sdc-distribute-status-block { - margin: 5px; - padding: 5px; - } - - .blue-font { - .a_16_m; - - } - - &:hover { - background-color: @tlv_color_u; - } - - } - - } - - .w-sdc-distribute-omfComponent-block { - background-color: white; - margin: 0 30px; - padding: 8px 10px; - border: 1px solid @border_color_f; - - .omfComponent-table-head { - margin-bottom: 5px; - background-color: @tlv_color_u; - .title { - padding: 6px 10px; - border-left: 1px solid @border_color_f; - &:first-child { - border: none; - } - } - } - - .omfComponent-table-row { - border-bottom: 1px solid @border_color_f; - &.row-0 { - border-top: 1px solid @border_color_f; - } - .w-sdc-distribute-cell { - padding: 10px; - border-left: 1px solid @border_color_f; - &:last-child { - border-right: 1px solid @border_color_f; - } - &.item-5 { - .m_14_m; - } - } - } - - .distribution-url { - - } - - .w-sdc-distribute-row.extends { - border-Left: solid 4px @main_color_c; - .item-1 { - border: none; - } - - } - - .item-1 { - width: 20%; - } - .item-2 { - width: 20%; - } - - .item-3 { - width: 24%; - display: flex; - } - - .item-4 { - width: 18%; - } - - .item-5 { - width: 18%; - } - } - - .w-sdc-distribute-url-block { - - padding: 10px 15px; - border: none; - border-right: 1px solid @border_color_f; - border-bottom: 1px solid @border_color_f; - width: 100%; - li { - border: none; - span { - padding-right: 30px; - .m_12_r; - } - } - - } - } - - } -} - diff --git a/catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts index b4529700cf..e2709281b7 100644 --- a/catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts +++ b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,11 +22,13 @@ import * as _ from "lodash"; import {ModalsHandler, ValidationUtils, EVENTS, CHANGE_COMPONENT_CSAR_VERSION_FLAG, ComponentType, DEFAULT_ICON, ResourceType, ComponentState, instantiationType, ComponentFactory} from "app/utils"; -import {CacheService, EventListenerService, ProgressService, OnboardingService} from "app/services"; +import { EventListenerService, ProgressService} from "app/services"; +import {CacheService, OnboardingService, ImportVSPService} from "app/services-ng2"; import {IAppConfigurtaion, IValidate, IMainCategory, Resource, ISubCategory,Service, ICsarComponent, Component} from "app/models"; import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model"; import {Dictionary} from "lodash"; import { PREVIOUS_CSAR_COMPONENT } from "../../../../utils/constants"; +import { Observable, Subject } from "rxjs"; export class Validation { @@ -37,7 +39,6 @@ export class Validation { VendorNameValidationPattern:RegExp; VendorModelNumberValidationPattern:RegExp; commentValidationPattern:RegExp; - projectCodeValidationPattern:RegExp; } export class componentCategories {//categories field bind to this obj in order to solve this bug: DE242059 @@ -61,7 +62,7 @@ export interface IGeneralScope extends IWorkspaceViewModelScope { isShowFileBrowse:boolean; isShowOnboardingSelectionBrowse:boolean; importedToscaBrowseFileText:string; - importCsarProgressKey:string; + importCsarProProgressKey:string; browseFileLabel:string; componentCategories:componentCategories; instantiationTypes:Array; @@ -86,6 +87,7 @@ export interface IGeneralScope extends IWorkspaceViewModelScope { possibleToUpdateIcon():boolean; } +// tslint:disable-next-line:max-classes-per-file export class GeneralViewModel { static '$inject' = [ @@ -100,7 +102,6 @@ export class GeneralViewModel { 'CommentValidationPattern', 'ValidationUtils', 'sdcConfig', - 'ProjectCodeValidationPattern', '$state', 'ModalsHandler', 'EventListenerService', @@ -109,8 +110,10 @@ export class GeneralViewModel { '$interval', '$filter', '$timeout', - 'Sdc.Services.OnboardingService', - 'ComponentFactory' + 'OnboardingService', + 'ComponentFactory', + 'ImportVSPService', + '$stateParams' ]; constructor(private $scope:IGeneralScope, @@ -124,7 +127,6 @@ export class GeneralViewModel { private CommentValidationPattern:RegExp, private ValidationUtils:ValidationUtils, private sdcConfig:IAppConfigurtaion, - private ProjectCodeValidationPattern:RegExp, private $state:ng.ui.IStateService, private ModalsHandler:ModalsHandler, private EventListenerService:EventListenerService, @@ -133,8 +135,10 @@ export class GeneralViewModel { protected $interval:any, private $filter:ng.IFilterService, private $timeout:ng.ITimeoutService, - private onBoardingService:OnboardingService, - private ComponentFactory:ComponentFactory) { + private onBoardingService: OnboardingService, + private ComponentFactory:ComponentFactory, + private importVSPService: ImportVSPService, + private $stateParams: any) { this.initScopeValidation(); this.initScopeMethods(); @@ -153,13 +157,11 @@ export class GeneralViewModel { this.$scope.validation.VendorNameValidationPattern = this.VendorNameValidationPattern; this.$scope.validation.VendorModelNumberValidationPattern = this.VendorModelNumberValidationPattern; this.$scope.validation.commentValidationPattern = this.CommentValidationPattern; - this.$scope.validation.projectCodeValidationPattern = this.ProjectCodeValidationPattern; }; - private loadOnboardingFileCache = ():ng.IPromise> =>{ - + private loadOnboardingFileCache = (): Observable>> => { let onboardCsarFilesMap:Dictionary>; - let onSuccess = (vsps:Array) =>{ + let onSuccess = (vsps:Array) => { onboardCsarFilesMap = {}; _.each(vsps, (vsp:ICsarComponent)=>{ onboardCsarFilesMap[vsp.packageId] = onboardCsarFilesMap[vsp.packageId] || {}; @@ -170,8 +172,8 @@ export class GeneralViewModel { }; let onError = (): void =>{ console.log("Error getting onboarding list"); - }; - return this.onBoardingService.getOnboardingVSPs().then(onSuccess, onError); + }; + return this.onBoardingService.getOnboardingVSPs().map(onSuccess, onError); }; private setImportedFileText = ():void => { @@ -179,7 +181,7 @@ export class GeneralViewModel { if(!this.$scope.isShowOnboardingSelectionBrowse) return; //these variables makes it easier to read this logic - let csarUUID:string = (this.$scope.component).csarUUID; + let csarUUID:string = (this.$scope.component).csarUUID; let csarVersion:string = (this.$scope.component).csarVersion; let onboardCsarFilesMap:Dictionary> = this.cacheService.get('onboardCsarFilesMap'); @@ -187,21 +189,25 @@ export class GeneralViewModel { if(this.$scope.component.vspArchived){ this.$scope.importedToscaBrowseFileText = 'VSP is archived'; } else { - this.$scope.importedToscaBrowseFileText = onboardCsarFilesMap[csarUUID][csarVersion]; + if(this.$stateParams.componentCsar && this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN' && !this.$scope.isCreateMode()) { + this.$scope.importedToscaBrowseFileText = this.$scope.originComponent.name + ' (' + (this.$scope.originComponent as Resource).csarVersion + ')'; + } else { + this.$scope.importedToscaBrowseFileText = onboardCsarFilesMap[csarUUID][csarVersion]; + } } } - + if(this.$scope.component.vspArchived || (onboardCsarFilesMap && onboardCsarFilesMap[csarUUID] && onboardCsarFilesMap[csarUUID][csarVersion])){ //check that the file name is already in cache assignFileName(); } else { - this.loadOnboardingFileCache().then((onboardingFiles) => { + this.loadOnboardingFileCache().subscribe((onboardingFiles) => { onboardCsarFilesMap = onboardingFiles; this.cacheService.set('onboardCsarFilesMap', onboardingFiles); assignFileName(); }, ()=> {}); } - + } isCreateModeAvailable(verifyObj:string): boolean { @@ -211,10 +217,9 @@ export class GeneralViewModel { private initScope = ():void => { - this.$scope.importCsarProgressKey = "importCsarProgressKey"; - this.$scope.browseFileLabel = this.$scope.component.isResource() && (this.$scope.component).resourceType === ResourceType.VF ? "Upload file" : "Upload VFC"; + this.$scope.browseFileLabel = this.$scope.component.isResource() && (this.$scope.component).resourceType === ResourceType.VF ? 'VSP' : 'Upload VFC'; this.$scope.progressService = this.progressService; this.$scope.componentCategories = new componentCategories(); this.$scope.componentCategories.selectedCategory = this.$scope.component.selectedCategory; @@ -236,7 +241,7 @@ export class GeneralViewModel { if (resource.importedFile) { // Component has imported file. this.$scope.isShowFileBrowse = true; } - if (this.$scope.isEditMode() && resource.resourceType == ResourceType.VF && !resource.csarUUID) { + if (resource.resourceType === ResourceType.VF && !resource.csarUUID) { this.$scope.isShowFileBrowse = true; } } else if(this.$scope.component.isService()){ @@ -244,30 +249,35 @@ export class GeneralViewModel { this.$scope.initInstantiationTypes(); } - // Work around to change the csar version - if (this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG)) { - //(this.$scope.component).csarVersion = this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG); - this.cacheService.remove(CHANGE_COMPONENT_CSAR_VERSION_FLAG); - this.$scope.updateUnsavedFileFlag(true); + if (this.cacheService.get(PREVIOUS_CSAR_COMPONENT)) { //keep the old component in the cache until checkout, so we dont need to pass it around + this.$scope.setOriginComponent(this.cacheService.get(PREVIOUS_CSAR_COMPONENT)); + this.cacheService.remove(PREVIOUS_CSAR_COMPONENT); + } - if (!this.$scope.isViewMode() && this.cacheService.get(PREVIOUS_CSAR_COMPONENT)) { //keep the old component in the cache until checkout, so we dont need to pass it around - this.$scope.setOriginComponent(this.cacheService.get(PREVIOUS_CSAR_COMPONENT)); - this.cacheService.remove(PREVIOUS_CSAR_COMPONENT); + if (this.$stateParams.componentCsar && !this.$scope.isCreateMode()) { + this.$scope.updateUnsavedFileFlag(true); + // We are coming from update VSP modal we need to automatically checkout (if needed) and save the VF + if (this.$scope.component.lifecycleState !== ComponentState.NOT_CERTIFIED_CHECKOUT) { + // Checkout is needed after that a save will be invoked in workspace-view.handleLifeCycleStateChange + this.EventListenerService.notifyObservers(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE, 'checkOut'); + // if(this.$scope.component.lifecycleState !== 'NOT_CERTIFIED_CHECKIN') { + // (this.$scope.component).csarVersion = this.$stateParams.componentCsar.csarVersion; + // } + } else { + this.$scope.save(); } } - // Init the decision if to show onboarding - if (this.$scope.component.isResource() && this.$scope.isEditMode() && - ((this.$scope.component).resourceType == ResourceType.VF || - (this.$scope.component).resourceType == ResourceType.PNF) - && (this.$scope.component).csarUUID) { + if (this.$scope.component.isResource() && + (this.$scope.component as Resource).resourceType === ResourceType.VF || + (this.$scope.component as Resource).resourceType === ResourceType.PNF && (this.$scope.component as Resource).csarUUID) { this.$scope.isShowOnboardingSelectionBrowse = true; this.setImportedFileText(); } else { this.$scope.isShowOnboardingSelectionBrowse = false; } - + //init file extensions based on the file that was imported. if (this.$scope.component.isResource() && (this.$scope.component).importedFile) { @@ -304,7 +314,7 @@ export class GeneralViewModel { this.$scope.originComponent.contactId = this.$scope.component.contactId; } - + this.$scope.$on('$destroy', () => { this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE); this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE); @@ -313,7 +323,7 @@ export class GeneralViewModel { }; // Convert category string MainCategory_#_SubCategory to Array with one item (like the server except) - private convertCategoryStringToOneArray = ():Array => { + private convertCategoryStringToOneArray = ():IMainCategory[] => { let tmp = this.$scope.component.selectedCategory.split("_#_"); let mainCategory = tmp[0]; let subCategory = tmp[1]; @@ -333,14 +343,14 @@ export class GeneralViewModel { } let tmpSelected = mainCategoryClone; - let result:Array = []; + let result:IMainCategory[] = []; result.push(tmpSelected); return result; }; private updateComponentNameInBreadcrumbs = ():void => { - //update breadcrum after changing name + // update breadcrum after changing name this.$scope.breadcrumbsModel[1].updateSelectedMenuItemText(this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name); this.$scope.updateMenuComponentName(this.$scope.component.name); }; @@ -436,24 +446,20 @@ export class GeneralViewModel { if(this.$scope.component.vspArchived) return; let csarUUID = (this.$scope.component).csarUUID; let csarVersion = (this.$scope.component).csarVersion; - this.ModalsHandler.openOnboadrdingModal('Update', csarUUID, csarVersion).then((result)=> { - - if(result){ - this.ComponentFactory.getComponentWithMetadataFromServer(result.type.toUpperCase(), result.previousComponent.uniqueId).then( - (component:Component)=> { - if (result.componentCsar && component.isResource()){ - this.cacheService.set(PREVIOUS_CSAR_COMPONENT, angular.copy(component)); - component = this.ComponentFactory.updateComponentFromCsar(result.componentCsar, component); - } - - this.$scope.setComponent(component); - this.$scope.updateUnsavedFileFlag(true); - this.setImportedFileText(); - }, ()=> { - // ERROR - }); - } - }, () => {}); + this.importVSPService.openOnboardingModal(csarUUID, csarVersion).subscribe((result) => { + this.ComponentFactory.getComponentWithMetadataFromServer(result.type.toUpperCase(), result.previousComponent.uniqueId).then( + (component:Component)=> { + if (result.componentCsar && component.isResource()){ + this.cacheService.set(PREVIOUS_CSAR_COMPONENT, angular.copy(component)); + component = this.ComponentFactory.updateComponentFromCsar(result.componentCsar, component); + } + this.$scope.setComponent(component); + this.$scope.save(); + this.setImportedFileText(); + }, ()=> { + // ERROR + }); + }) }; this.$scope.updateIcon = ():void => { @@ -491,17 +497,17 @@ export class GeneralViewModel { return; } - let subtype:string = ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined; + const subtype:string = ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined; - let onFailed = (response) => { - //console.info('onFaild', response); - //this.$scope.isLoading = false; + const onFailed = (response) => { + // console.info('onFaild', response); + // this.$scope.isLoading = false; }; - let onSuccess = (validation:IValidate) => { - this.$scope.editForm["componentName"].$setValidity('nameExist', validation.isValid); + const onSuccess = (validation:IValidate) => { + this.$scope.editForm['componentName'].$setValidity('nameExist', validation.isValid); if (validation.isValid) { - //update breadcrumb after changing name + // update breadcrumb after changing name this.updateComponentNameInBreadcrumbs(); } }; @@ -522,48 +528,57 @@ export class GeneralViewModel { && !this.$scope.editForm["componentName"].$error.pattern && (!this.$scope.originComponent.name || this.$scope.component.name.toUpperCase() !== this.$scope.originComponent.name.toUpperCase()) ) { - if (!(this.$scope.componentType === ComponentType.RESOURCE && (this.$scope.component).csarUUID !== undefined) + if (!(this.$scope.componentType === ComponentType.RESOURCE && (this.$scope.component as Resource).csarUUID !== undefined) ) { this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed); } - } else if (this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) { + } else if (this.$scope.editForm && this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) { // Clear the error - this.$scope.editForm["componentName"].$setValidity('nameExist', true); + this.$scope.editForm['componentName'].$setValidity('nameExist', true); } } }; this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE, (nextState) => { - if (this.$state.current.data.unsavedChanges && this.$scope.isValidForm){ + if (this.$state.current.data.unsavedChanges && this.$scope.isValidForm) { this.$scope.save().then(() => { this.$scope.handleChangeLifecycleState(nextState); }, () => { - console.error("Save failed, unable to change lifecycle state to " + nextState); + console.error('Save failed, unable to change lifecycle state to ' + nextState); }); } else if(!this.$scope.isValidForm){ - console.error("Form is not valid"); + console.error('Form is not valid'); } else { let newCsarVersion:string; - if(this.$scope.unsavedFile){ - newCsarVersion = (this.$scope.component).csarVersion; + if(this.$scope.unsavedFile) { + newCsarVersion = (this.$scope.component as Resource).csarVersion; + } + if(this.$stateParams.componentCsar && !this.$scope.isCreateMode()) { + const onError = (): void => { + if (this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN') { + this.$scope.revert(); + } + }; + this.$scope.handleChangeLifecycleState(nextState, newCsarVersion, onError); + + } else { + this.$scope.handleChangeLifecycleState(nextState, newCsarVersion); } - this.$scope.handleChangeLifecycleState(nextState, newCsarVersion); } }); - this.$scope.revert = ():void => { - //in state of import file leave the file in place + // in state of import file leave the file in place this.$scope.setComponent(this.ComponentFactory.createComponent(this.$scope.originComponent)); if (this.$scope.component.isResource() && this.$scope.restoreFile) { - (this.$scope.component).importedFile = angular.copy(this.$scope.restoreFile); - } - - this.setImportedFileText(); - this.$scope.updateBreadcrumbs(this.$scope.component); //update on workspace + (this.$scope.component as Resource).importedFile = angular.copy(this.$scope.restoreFile); + } + + this.setImportedFileText(); + this.$scope.updateBreadcrumbs(this.$scope.component); // update on workspace this.$scope.componentCategories.selectedCategory = this.$scope.originComponent.selectedCategory; this.setUnsavedChanges(false); @@ -573,8 +588,8 @@ export class GeneralViewModel { this.$scope.onImportFileChange = () => { - if( !this.$scope.restoreFile && this.$scope.editForm.fileElement.value && this.$scope.editForm.fileElement.value.filename || //if file started empty but we have added a new one - this.$scope.restoreFile && !angular.equals(this.$scope.restoreFile, this.$scope.editForm.fileElement.value)){ //or file was swapped for a new one + if( !this.$scope.restoreFile && this.$scope.editForm.fileElement.value && this.$scope.editForm.fileElement.value.filename || // if file started empty but we have added a new one + this.$scope.restoreFile && !angular.equals(this.$scope.restoreFile, this.$scope.editForm.fileElement.value)){ // or file was swapped for a new one this.$scope.updateUnsavedFileFlag(true); } else { this.$scope.updateUnsavedFileFlag(false); @@ -582,46 +597,46 @@ export class GeneralViewModel { } }; - this.$scope.$watchCollection('component.name', (newData:any):void => { + this.$scope.$watchCollection('component.name', (newData: any): void => { this.$scope.validateName(false); }); // Notify the parent if this step valid or not. - this.$scope.$watch("editForm.$valid", (newVal, oldVal) => { + this.$scope.$watch('editForm.$valid', (newVal, oldVal) => { this.$scope.setValidState(newVal); }); - this.$scope.$watch("editForm.$dirty", (newVal, oldVal) => { + this.$scope.$watch('editForm.$dirty', (newVal, oldVal) => { if (newVal && !this.$scope.isCreateMode()) { this.setUnsavedChanges(true); } }); - this.$scope.onCategoryChange = ():void => { + this.$scope.onCategoryChange = (): void => { this.$scope.component.selectedCategory = this.$scope.componentCategories.selectedCategory; this.$scope.component.categories = this.convertCategoryStringToOneArray(); this.$scope.component.icon = DEFAULT_ICON; }; - this.$scope.onEcompGeneratedNamingChange = ():void =>{ - if(!(this.$scope.component).ecompGeneratedNaming){ - (this.$scope.component).namingPolicy = ''; + this.$scope.onEcompGeneratedNamingChange = (): void => { + if (!(this.$scope.component as Service).ecompGeneratedNaming) { + (this.$scope.component as Service).namingPolicy = ''; } }; - this.$scope.onVendorNameChange = (oldVendorName:string):void => { + this.$scope.onVendorNameChange = (oldVendorName: string): void => { if (this.$scope.component.icon === oldVendorName) { this.$scope.component.icon = DEFAULT_ICON; } }; this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE, this.$scope.reload); - }; + } - private setUnsavedChanges = (hasChanges:boolean):void => { + private setUnsavedChanges = (hasChanges: boolean): void => { this.$state.current.data.unsavedChanges = hasChanges; - }; + } } diff --git a/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html index 07f1e4d6ed..86f1feba0c 100644 --- a/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html +++ b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html @@ -13,13 +13,12 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> -
    -
    +
    Click save to update to the new VSP
    - @@ -160,7 +159,7 @@
    - + @@ -173,17 +172,17 @@ on-file-changed-in-directive="onImportFileChange" extensions="{{importedFileExtension}}" default-text="'Browse to select file'" - data-ng-class="{'error':!(isEditMode()&&component.resourceType=='VF') && (!editForm.fileElement.$valid || !component.importedFile.filename)}"> + >
    - +
    {{(fileModel && fileModel.filename) || importedToscaBrowseFileText }}
    - -
    Browse
    + +
    Browse
    @@ -218,28 +217,6 @@
    - -
    - - - -
    - - - -
    -
    -
    @@ -401,6 +378,27 @@
    + +
    + + +
    + + +
    +
    + +
    diff --git a/catalog-ui/src/app/view-models/workspace/tabs/general/general.less b/catalog-ui/src/app/view-models/workspace/tabs/general/general.less index b60e4b8de4..8b2cc01d75 100644 --- a/catalog-ui/src/app/view-models/workspace/tabs/general/general.less +++ b/catalog-ui/src/app/view-models/workspace/tabs/general/general.less @@ -27,6 +27,7 @@ .file-upload-browse-btn { .noselect; .bg_n; + color:#191919; padding: 4px 6px; cursor: pointer; z-index: 999; @@ -35,10 +36,6 @@ text-align: center; border-left: solid 1px #cfcfcf; - &.disabled { - cursor: default; - } - &:hover:not(.disabled) { background-color: #dbdee2; } diff --git a/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts deleted file mode 100644 index 47a96fb385..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts +++ /dev/null @@ -1,158 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import * as _ from "lodash"; -import {ModalsHandler} from "app/utils"; -import {SharingService} from "app/services"; -import {IAppConfigurtaion, ArtifactModel, IFileDownload} from "app/models"; -import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model"; -import {ComponentServiceNg2} from "../../../../ng2/services/component-services/component.service"; -import {ArtifactGroupModel} from "../../../../models/artifacts"; -import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response"; - -export interface IInformationArtifactsScope extends IWorkspaceViewModelScope { - artifacts:Array; - tableHeadersList:Array; - artifactType:string; - isResourceInstance:boolean; - downloadFile:IFileDownload; - isLoading:boolean; - sortBy:string; - reverse:boolean; - - getTitle():string; - addOrUpdate(artifact:ArtifactModel):void; - delete(artifact:ArtifactModel):void; - download(artifact:ArtifactModel):void; - clickArtifactName(artifact:any):void; - openEditEnvParametersModal(artifactResource:ArtifactModel):void; - sort(sortBy:string):void; - showNoArtifactMessage():boolean; -} - -export class InformationArtifactsViewModel { - - static '$inject' = [ - '$scope', - '$filter', - '$state', - 'sdcConfig', - 'ModalsHandler', - 'ComponentServiceNg2' - ]; - - constructor(private $scope:IInformationArtifactsScope, - private $filter:ng.IFilterService, - private $state:any, - private sdcConfig:IAppConfigurtaion, - private ModalsHandler:ModalsHandler, - private ComponentServiceNg2: ComponentServiceNg2) { - this.initInformationalArtifacts(); - } - - private initInformationalArtifacts = ():void => { - if(!this.$scope.component.artifacts) { - this.$scope.isLoading = true; - this.ComponentServiceNg2.getComponentInformationalArtifacts(this.$scope.component).subscribe((response:ComponentGenericResponse) => { - this.$scope.component.artifacts = response.artifacts; - this.initScope(); - this.$scope.isLoading = false; - }); - } else { - this.initScope(); - } - } - - private initScope = ():void => { - - this.$scope.isLoading = false; - this.$scope.sortBy = 'artifactDisplayName'; - this.$scope.reverse = false; - this.$scope.setValidState(true); - this.$scope.artifactType = 'informational'; - this.$scope.getTitle = ():string => { - return this.$filter("resourceName")(this.$scope.component.name) + ' Artifacts'; - - }; - - this.$scope.tableHeadersList = [ - {title: 'Name', property: 'artifactDisplayName'}, - {title: 'Type', property: 'artifactType'}, - {title: 'Version', property: 'artifactVersion'}, - {title: 'UUID', property: 'artifactUUID'} - ]; - - this.$scope.artifacts = _.values(this.$scope.component.artifacts); - this.$scope.sort = (sortBy:string):void => { - this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false; - this.$scope.sortBy = sortBy; - }; - - - this.$scope.addOrUpdate = (artifact:ArtifactModel):void => { - artifact.artifactGroupType = 'INFORMATIONAL'; - this.ModalsHandler.openArtifactModal(artifact, this.$scope.component).then(() => { - this.$scope.artifacts = _.values(this.$scope.component.artifacts); - }); - }; - - this.$scope.showNoArtifactMessage = ():boolean => { - let artifacts:any = []; - artifacts = _.filter(this.$scope.artifacts, (artifact:ArtifactModel)=> { - return artifact.esId; - }); - - if (artifacts.length === 0) { - return true; - } - return false; - }; - - this.$scope.delete = (artifact:ArtifactModel):void => { - - let onOk = ():void => { - this.$scope.isLoading = true; - let onSuccess = ():void => { - this.$scope.isLoading = false; - this.$scope.artifacts = _.values(this.$scope.component.artifacts); - }; - - let onFailed = (error:any):void => { - console.log('Delete artifact returned error:', error); - this.$scope.isLoading = false; - }; - - this.$scope.component.deleteArtifact(artifact.uniqueId, artifact.artifactLabel).then(onSuccess, onFailed); - }; - - let title:string = this.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TITLE"); - let message:string = this.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TEXT", "{'name': '" + artifact.artifactDisplayName + "'}"); - this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk); - }; - - this.$scope.clickArtifactName = (artifact:any) => { - if (!artifact.esId) { - this.$scope.addOrUpdate(artifact); - } - - }; - } -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view.html b/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view.html deleted file mode 100644 index eacadb376c..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view.html +++ /dev/null @@ -1,82 +0,0 @@ - - -
    -
    Add
    -
    -
    -
    -
    {{header.title}} - -
    -
    -
    -
    - -
    - There are no information artifacts to display -
    -
    - -
    - - {{artifact.artifactDisplayName}} -
    - -
    - {{artifact.artifactType}} -
    - -
    - {{artifact.artifactVersion}} -
    - -
    - {{artifact.artifactUUID}} -
    - -
    - - - -
    -
    -
    - - -
    -
    -
    -
    -
    diff --git a/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts.less b/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts.less deleted file mode 100644 index 5e69c44e9b..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts.less +++ /dev/null @@ -1,57 +0,0 @@ -.workspace-information-artifact { - width: 93%; - display: inline-block; - .w-sdc-classic-btn { - float: right; - margin-bottom: 10px; - } - - .table{ - height: 490px; - margin-bottom: 0; - } - - .table-container-flex { - margin-top: 0; - - .item-opened{ - word-wrap: break-word; - } - - .text{ - overflow: hidden; - text-overflow: ellipsis; - display: inline-block; - white-space: nowrap; - } - - .flex-item:nth-child(1) { - flex-grow: 15; - .hand; - span.table-arrow { - margin-right: 7px; - } - } - - .flex-item:nth-child(2) { - flex-grow: 6; - } - - .flex-item:nth-child(3) { - flex-grow: 3; - } - - .flex-item:nth-child(4) { - flex-grow: 20; - } - - .flex-item:nth-child(5) { - flex-grow: 5; - padding-top: 10px; - } - - } - -} - - diff --git a/catalog-ui/src/app/view-models/workspace/tabs/inputs/inputs.less b/catalog-ui/src/app/view-models/workspace/tabs/inputs/inputs.less deleted file mode 100644 index 17c18e1741..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/inputs/inputs.less +++ /dev/null @@ -1,225 +0,0 @@ -.workspace-inputs { - - .sdc-workspace-container .w-sdc-main-right-container .w-sdc-main-container-body-content { - padding: 25px 8% 25px 8%; - } - - .w-sdc-main-container .w-sdc-main-right-container > div:first-child { - /* scroll fix */ - padding-bottom: 0px; - } - - - width: 100%; - display: flex; - - .text { - padding-left: 15px; - .no-overflow; - } - - .title-text { - color: @main_color_m; - .f-type._13_m; - .bold; - text-overflow: ellipsis; - overflow: hidden; - } - - .no-overflow { - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; - } - - .title-blue-text { - color: @main_color_a; - .f-type._13_m; - - &.property-name-text { - padding-right: 13px; - border-right: 1px solid rgba(120, 136, 148, 0.26); - flex-grow: 1; - .no-overflow; - } - } - - .instance-name-text { - flex-grow: 1; - } - - ng-include { - width: 45%; - } - - .w-sdc-inputs-search { - padding: 10px 20px 20px 0; - white-space: nowrap; - position: relative; - width: 60%; - height: 64px; - - .inputs-search-icon { - top: 9px; - right: 11px; - } - - .magnification-white { - .sprite-new; - .search-white-icon; - .hand; - } - - .search-icon-container { - width: 35px; - height: 30px; - background-color: @main_color_a; - white-space: nowrap; - float: right; - position: relative; - bottom: 31px; - right: 1px; - border-radius: 0px 4px 4px 0px; - .hand - } - } - - .total-inputs-count { - width: 100%; - font-weight: bold; - text-align: left; - } - - .new-input-button { - margin: 9px 0 0 0; - } - - .w-sdc-inputs-search-input { - border: 1px solid @color_e; - .border-radius(4px); - height: 32px; - margin: 0; - padding: 0px 28px 3px 10px; - vertical-align: 4px; - width: 100%; - outline: none; - font-style: italic; - } - - .w-sdc-classic-btn { - float: right; - margin-bottom: 10px; - } - - .prop-to-input-button { - position: absolute; - top: 50%; - margin-right: -20px; - margin-bottom: -10px; - - } - - .table-container-flex { - - .flex-item { - line-height: 22px; - } - .expand-collapse-table-row { - - .data-row { - background: @tlv_color_u; - .hand; - align-items: center; - padding: 0 12px; - margin: 1px 0px 1px 0px; - min-height: 40px; - } - - .data-row:hover { - .bg_j; - } - } - } - - .table { - height: 640px; - margin-bottom: 0; - clear: both; - - .empty-row { - padding: 3px; - } - - .flex-item { - line-height: 22px; - } - - .table-header { - - line-height: 14px; - background-color: @main_color_a; - color: @main_color_p; - text-align: left; - padding: 7px 5px 7px 10px; - .f-type._14_m; - } - .head { - background-color: #e6e6e6; - } - - .body { - .scrollbar-container { - .perfect-scrollbar; - max-height: 610px; - } - - .expand-collapse-inputs-table-icon { - .hand; - .sprite-new; - .arrow-up; - transition: .3s all; - position: relative; - left: 8px; - border: none !important; - padding: 0px 10px 0px 10px; - } - - .table-col-text { - margin-left: 14px; - } - } - } - - .inputs-header { - width: 100%; - position: relative; - bottom: 31px; - } - - .inputs-tables-container { - width: 100%; - min-width: 100%; - display: flex; - } - - .inputs-button-container { - width: 8%; - min-width: 8%; - display: flex; - - .right-arrow-btn { - .sprite-new; - .blue-right-arrow-circle; - margin: auto; - cursor: pointer; - } - } - - .table-container-flex { - margin-top: 0; - width: 46%; - min-width: 46%; - display: inline-block; - float: left; - } -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/interface-operation/interface-operation-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/interface-operation/interface-operation-view-model.ts index 180d78954a..83a2be2a60 100644 --- a/catalog-ui/src/app/view-models/workspace/tabs/interface-operation/interface-operation-view-model.ts +++ b/catalog-ui/src/app/view-models/workspace/tabs/interface-operation/interface-operation-view-model.ts @@ -27,7 +27,6 @@ * limitations under the License. */ - 'use strict'; import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model"; diff --git a/catalog-ui/src/app/view-models/workspace/tabs/interface-operation/interface-operation-view.html b/catalog-ui/src/app/view-models/workspace/tabs/interface-operation/interface-operation-view.html index 0e7c355c47..236289feff 100644 --- a/catalog-ui/src/app/view-models/workspace/tabs/interface-operation/interface-operation-view.html +++ b/catalog-ui/src/app/view-models/workspace/tabs/interface-operation/interface-operation-view.html @@ -13,7 +13,6 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> -
    -
    diff --git a/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view.html b/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view.html index a1efb33301..01343a35ac 100644 --- a/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view.html +++ b/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view.html @@ -13,7 +13,6 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> -
    diff --git a/catalog-ui/src/app/view-models/workspace/tabs/plugins/plugins-context-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/plugins/plugins-context-view-model.ts deleted file mode 100644 index d3ccbe3325..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/plugins/plugins-context-view-model.ts +++ /dev/null @@ -1,94 +0,0 @@ -/* - -* Copyright (c) 2018 AT&T Intellectual Property. - -* - -* Licensed under the Apache License, Version 2.0 (the "License"); - -* you may not use this file except in compliance with the License. - -* You may obtain a copy of the License at - -* - -* http://www.apache.org/licenses/LICENSE-2.0 - -* - -* Unless required by applicable law or agreed to in writing, software - -* distributed under the License is distributed on an "AS IS" BASIS, - -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -* See the License for the specific language governing permissions and - -* limitations under the License. - -*/ - -import {IUserProperties, Plugin} from "app/models"; -import {CacheService} from "app/services"; -import {PluginsService} from "../../../../ng2/services/plugins.service"; -import {IWorkspaceViewModelScope} from "../../workspace-view-model"; - - -interface IPluginsContextViewModelScope extends IWorkspaceViewModelScope { - plugin: Plugin; - user: IUserProperties; - queryParams: Object; - isLoading: boolean; - show: boolean; - - onLoadingDone(plugin: Plugin): void; -} - -export class PluginsContextViewModel { - static '$inject' = [ - '$scope', - '$stateParams', - 'Sdc.Services.CacheService', - 'PluginsService' - ]; - - constructor(private $scope: IPluginsContextViewModelScope, - private $stateParams: any, - private cacheService: CacheService, - private pluginsService: PluginsService) { - - this.initScope(); - } - - private initScope = (): void => { - this.$scope.show = false; - this.$scope.plugin = this.pluginsService.getPluginByStateUrl(this.$stateParams.path); - this.$scope.user = this.cacheService.get('user'); - - this.$scope.isLoading = true; - - this.$scope.queryParams = { - userId: this.$scope.user.userId, - userRole: this.$scope.user.role, - displayType: "context", - contextType: this.$scope.component.getComponentSubType(), - uuid: this.$scope.component.uuid, - lifecycleState: this.$scope.component.lifecycleState, - isOwner: this.$scope.component.lastUpdaterUserId === this.$scope.user.userId, - version: this.$scope.component.version, - parentUrl: window.location.origin, - eventsClientId: this.$scope.plugin.pluginId - }; - - if (this.$stateParams.queryParams) { - _.assign(this.$scope.queryParams, this.$stateParams.queryParams); - } - - this.$scope.onLoadingDone = (plugin: Plugin) => { - if (plugin.pluginId == this.$scope.plugin.pluginId) { - this.$scope.isLoading = false; - } - }; - - } -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/plugins/plugins-context-view.html b/catalog-ui/src/app/view-models/workspace/tabs/plugins/plugins-context-view.html deleted file mode 100644 index 44c04e4e71..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/plugins/plugins-context-view.html +++ /dev/null @@ -1,20 +0,0 @@ - - - -
    - -
    diff --git a/catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view-model.ts index b09662d7a2..9794209757 100644 --- a/catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view-model.ts +++ b/catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view-model.ts @@ -19,12 +19,12 @@ */ 'use strict'; -import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model"; -import {PropertyModel} from "app/models"; -import {ModalsHandler} from "app/utils"; -import {COMPONENT_FIELDS} from "../../../../utils/constants"; -import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response"; -import {ComponentServiceNg2} from "../../../../ng2/services/component-services/component.service"; +import { IWorkspaceViewModelScope } from "app/view-models/workspace/workspace-view-model"; +import { PropertyModel } from "app/models"; +import { ModalsHandler } from "app/utils"; +import { ComponentGenericResponse } from "../../../../ng2/services/responses/component-generic-response"; +import { ComponentServiceNg2 } from "../../../../ng2/services/component-services/component.service"; +import { SdcUiCommon, SdcUiServices, SdcUiComponents } from "onap-ui-angular"; interface IPropertiesViewModelScope extends IWorkspaceViewModelScope { tableHeadersList:Array; @@ -43,14 +43,16 @@ export class PropertiesViewModel { '$scope', '$filter', 'ModalsHandler', - 'ComponentServiceNg2' + 'ComponentServiceNg2', + 'ModalServiceSdcUI' ]; constructor(private $scope:IPropertiesViewModelScope, private $filter:ng.IFilterService, private ModalsHandler:ModalsHandler, - private ComponentServiceNg2:ComponentServiceNg2) { + private ComponentServiceNg2:ComponentServiceNg2, + private modalService: SdcUiServices.ModalService) { this.initComponentProperties(); } @@ -101,12 +103,13 @@ export class PropertiesViewModel { this.$scope.delete = (property:PropertyModel):void => { - let onOk = ():void => { + let onOk: Function = ():void => { this.$scope.component.deleteProperty(property.uniqueId); }; let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE"); let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}"); - this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk); + const okButton = {testId: "OK", text: "OK", type: SdcUiCommon.ButtonType.info, callback: onOk, closeModal: true} as SdcUiComponents.ModalButtonComponent; + this.modalService.openInfoModal(title, message, 'delete-modal', [okButton]); }; } } diff --git a/catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view.html b/catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view.html index 1505e8397d..1d8a2ff78c 100644 --- a/catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view.html +++ b/catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view.html @@ -13,7 +13,6 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> -
    Total Properties: {{component.properties.length}} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-editable-view.html b/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-editable-view.html deleted file mode 100644 index 566cc5fc2c..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-editable-view.html +++ /dev/null @@ -1,247 +0,0 @@ - - -
    - - -
    -
    -
    Requirements -
    -
    Capabilities -
    -
    -
    - -
    - - - {{mode === 'requirements' ? 'Add Requirement' : 'Add Capability'}} -
    -
    -
    - -
    -
    - - -
    {{mode === 'requirements' ? 'Add Requirement' : 'Add Capability'}}
    -
    -
    - -
    -
    -
    -
    - {{header.title}} - -
    -
    - -
    - -
    - There are no requirements to display - -
    -
    -
    -
    - {{(!req.isCreatedManually ? req.ownerName + '.' : '') + req.name}} -
    -
    - {{req.capability && cutToscaTypePrefix(req.capability, 'capabilities.')}} -
    -
    - {{req.node && cutToscaTypePrefix(req.node, "nodes.")}} -
    -
    - {{req.relationship && cutToscaTypePrefix(req.relationship, "relationships.")}} -
    -
    - {{req.minOccurrences}} - {{req.maxOccurrences}} -
    -
    - -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    - {{header.title}} - -
    -
    - -
    - -
    - There are no capabilities to display -
    -
    - -
    - - - {{(!capability.isCreatedManually ? capability.ownerName + '.' : '') + capability.name}} - -
    -
    - {{capability.type && cutToscaTypePrefix(capability.type, 'capabilities.')}} -
    - -
    -
    {{capability.description}} -
    -
    - -
    - {{capability.validSourceTypes.join(',')}} -
    - -
    - {{capability.minOccurrences}} - {{capability.maxOccurrences}} -
    - -
    - -
    -
    -
    -

    Properties

    -
    -
    -
    -
    - {{header.title}} - -
    -
    - -
    -
    -
    - {{property.name}} -
    -
    - {{property.type}} -
    -
    - {{property.schema.property.type}} -
    -
    - {{property.description}} -
    -
    -
    - -
    -
    -
    -
    -
    - -
    -
    -
    - diff --git a/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts deleted file mode 100644 index 14b45cbdf3..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts +++ /dev/null @@ -1,471 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -/** - * Created by rcohen on 9/22/2016. - */ -'use strict'; -import * as _ from "lodash"; -import {ComponentRef} from '@angular/core'; -import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model"; -import {ModalsHandler, ResourceType} from "app/utils"; -import {ComponentType} from "app/utils/constants"; -import { - Capability, PropertyModel, Requirement, Resource, - RelationshipTypesMap, NodeTypesMap, CapabilityTypesMap -} from "app/models"; -import {ComponentGenericResponse} from "app/ng2/services/responses/component-generic-response"; -import {ComponentServiceNg2} from "app/ng2/services/component-services/component.service"; -import {ToscaTypesServiceNg2} from "app/ng2/services/tosca-types.service"; -import {ModalComponent} from 'app/ng2/components/ui/modal/modal.component'; -import {ModalService} from 'app/ng2/services/modal.service'; -import {RequirementsEditorComponent} from 'app/ng2/pages/req-and-capabilities-editor/requirements-editor/requirements-editor.component'; -import {CapabilitiesEditorComponent} from 'app/ng2/pages/req-and-capabilities-editor/capabilities-editor/capabilities-editor.component'; -import {ModalService as ModalServiceSdcUI} from "sdc-ui/lib/angular/modals/modal.service"; -import {IModalConfig} from "sdc-ui/lib/angular/modals/models/modal-config"; -import {ModalButtonComponent} from "sdc-ui/lib/angular/components"; - -export class SortTableDefined { - reverse:boolean; - sortByField:string; -} - -class RequirementUI extends Requirement { - isCreatedManually: boolean; - - constructor(input: Requirement, componentUniqueId: string) { - super(input); - this.isCreatedManually = input.ownerId === componentUniqueId; - } -} -class CapabilityUI extends Capability { - isCreatedManually: boolean; - - constructor(input: Capability, componentUniqueId: string) { - super(input); - this.isCreatedManually = input.ownerId === componentUniqueId; - } -} - -interface IReqAndCapabilitiesViewModelScope extends IWorkspaceViewModelScope { - requirementsTableHeadersList:Array; - editableRequirementsTableHeadersList: Array; - capabilitiesTableHeadersList:Array; - editableCapabilitiesTableHeadersList: Array; - capabilityPropertiesTableHeadersList:Array; - requirementsSortTableDefined:SortTableDefined; - capabilitiesSortTableDefined:SortTableDefined; - propertiesSortTableDefined:SortTableDefined; - requirements: Array; - filteredRequirementsList: Array; - capabilities: Array; - filteredCapabilitiesList: Array; - mode:string; - filteredProperties:Array>; - searchText:string; - isEditable: boolean; - modalInstance: ComponentRef; - filter: {txt: string; show: boolean}; - - sort(sortBy: string, sortByTableDefined: SortTableDefined, autoCollapseCapabilitiesRows: boolean): void; - sortByIsCreatedManually(arrToSort: Array): Array; - updateProperty(property:PropertyModel, indexInFilteredProperties:number):void; - allCapabilitiesSelected(selected:boolean):void; - onAddBtnClicked(): void; - onEditRequirement(req: RequirementUI): void; - onEditCapability(cap: CapabilityUI): void; - onDeleteReq(event, req: RequirementUI): void; - onDeleteCap(event, cap: CapabilityUI): void; - onFilter(): void; - isListEmpty(): boolean; - onSwitchTab(): void; - onSearchIconClick(): void; - cutToscaTypePrefix(valToCut: string, textToStartCut: string): string; - isReadonly(): boolean; -} - -export class ReqAndCapabilitiesViewModel { - - static '$inject' = [ - '$scope', - '$filter', - 'ModalsHandler', - 'ComponentServiceNg2', - 'ToscaTypesServiceNg2', - 'ModalServiceNg2', - 'ModalServiceSdcUI' - ]; - - - constructor(private $scope:IReqAndCapabilitiesViewModelScope, - private $filter:ng.IFilterService, - private ModalsHandler:ModalsHandler, - private ComponentServiceNg2: ComponentServiceNg2, - private ToscaTypesServiceNg2: ToscaTypesServiceNg2, - private ModalServiceNg2: ModalService, - private ModalServiceSdcUI: ModalServiceSdcUI) { - - this.initCapabilitiesAndRequirements(); - this.fetchCapabilitiesRelatedData(); - } - - private initCapabilitiesAndRequirements = (): void => { - - this.$scope.isEditable = this.getIsEditableByComponentType(); - this.$scope.isLoading = true; - this.ComponentServiceNg2.getCapabilitiesAndRequirements(this.$scope.component.componentType, this.$scope.component.uniqueId).subscribe((response: ComponentGenericResponse) => { - this.$scope.component.capabilities = response.capabilities; - this.$scope.component.requirements = response.requirements; - this.initScope(); - this.$scope.isLoading = false; - }, () => { - this.$scope.isLoading = false; - }); - - } - - private openEditPropertyModal = (property:PropertyModel, indexInFilteredProperties:number):void => { - //...because there is not be api - _.forEach(this.$scope.filteredProperties[indexInFilteredProperties], (prop:PropertyModel)=> { - prop.readonly = true; - }); - this.ModalsHandler.openEditPropertyModal(property, this.$scope.component, this.$scope.filteredProperties[indexInFilteredProperties], false, "component", this.$scope.component.uniqueId).then(() => { - - }); - }; - - private initScope = (currentMode = 'requirements'): void => { - this.$scope.isReadonly = (): boolean => { - return this.$scope.isViewMode() || !this.$scope.isDesigner(); - }; - this.$scope.filter = {txt: '', show: false}; - this.$scope.requirementsSortTableDefined = { - reverse: false, - sortByField: this.$scope.isEditable ? 'other' : 'name' - }; - this.$scope.capabilitiesSortTableDefined = { - reverse: false, - sortByField: this.$scope.isEditable ? 'other' : 'name' - }; - this.$scope.propertiesSortTableDefined = { - reverse: false, - sortByField: 'name' - }; - - this.$scope.setValidState(true); - this.$scope.requirementsTableHeadersList = [ - {title: 'Name', property: 'name'}, - {title: 'Capability', property: 'capability'}, - {title: 'Node', property: 'node'}, - {title: 'Relationship', property: 'relationship'}, - {title: 'Connected To', property: ''}, - {title: 'Occurrences', property: ''} - ]; - this.$scope.capabilitiesTableHeadersList = [ - {title: 'Name', property: 'name'}, - {title: 'Type', property: 'type'}, - {title: 'Description', property: ''}, - {title: 'Valid Source', property: ''}, - {title: 'Occurrences', property: ''} - ]; - this.$scope.editableRequirementsTableHeadersList = [ - {title: 'Name', property: 'name'}, - {title: 'Capability', property: 'capability'}, - {title: 'Node', property: 'node'}, - {title: 'Relationship', property: 'relationship'}, - {title: 'Occurrences', property: 'occurrences'}, - {title: '●●●', property: 'other'} - ]; - this.$scope.editableCapabilitiesTableHeadersList = [ - {title: 'Name', property: 'name'}, - {title: 'Type', property: 'type'}, - {title: 'Description', property: 'description'}, - {title: 'Valid Sources', property: 'valid-sources'}, - {title: 'Occurrences', property: 'occurrences'}, - {title: '●●●', property: 'other'} - ]; - this.$scope.capabilityPropertiesTableHeadersList = [ - {title: 'Name', property: 'name'}, - {title: 'Type', property: 'type'}, - {title: 'Schema', property: 'schema.property.type'}, - {title: 'Description', property: 'description'}, - ]; - this.$scope.filteredProperties = []; - - this.$scope.mode = currentMode; - this.$scope.requirements = []; - _.forEach(this.$scope.component.requirements, (req:Array, capName)=> { - let reqUIList: Array = _.map(req, reqObj => new RequirementUI(reqObj, this.$scope.component.uniqueId)); - this.$scope.requirements = this.$scope.requirements.concat(reqUIList); - }); - this.$scope.filteredRequirementsList = this.$scope.requirements; - - this.$scope.capabilities = []; - _.forEach(this.$scope.component.capabilities, (cap:Array, capName)=> { - let capUIList: Array = _.map(cap, capObj => new CapabilityUI(capObj, this.$scope.component.uniqueId)); - this.$scope.capabilities = this.$scope.capabilities.concat(capUIList); - }); - - this.$scope.sortByIsCreatedManually = (arrToSort: Array): Array => { - return arrToSort.sort((elem1: RequirementUI|CapabilityUI, elem2: RequirementUI|CapabilityUI) => +elem2.isCreatedManually - (+elem1.isCreatedManually)); - }; - this.$scope.filteredCapabilitiesList = this.$scope.sortByIsCreatedManually(this.$scope.capabilities); - this.$scope.filteredRequirementsList = this.$scope.sortByIsCreatedManually(this.$scope.requirements); - - this.$scope.sort = (sortBy: string, sortByTableDefined: SortTableDefined, autoCollapseCapabilitiesRows: boolean): void => { - sortByTableDefined.reverse = (sortByTableDefined.sortByField === sortBy) ? !sortByTableDefined.reverse : false; - sortByTableDefined.sortByField = sortBy; - if (autoCollapseCapabilitiesRows) { - this.$scope.allCapabilitiesSelected(false); - } - }; - - this.$scope.updateProperty = (property:PropertyModel, indexInFilteredProperties:number):void => { - this.openEditPropertyModal(property, indexInFilteredProperties); - }; - - this.$scope.allCapabilitiesSelected = (selected:boolean):void => { - _.forEach(this.$scope.capabilities, (cap:Capability)=> { - cap.selected = selected; - }); - }; - this.$scope.onAddBtnClicked = (): void => { - switch (this.$scope.mode) { - case 'requirements': - this.openRequirementsModal(); - break; - case 'capabilities': - this.openCapabilitiesModal(); - break; - } - }; - this.$scope.onEditRequirement = (req: RequirementUI): void => { - this.openRequirementsModal(req); - }; - this.$scope.onEditCapability = (cap: CapabilityUI): void => { - this.openCapabilitiesModal(cap); - }; - this.$scope.onDeleteReq = (event: Event, req: RequirementUI): void => { - event.stopPropagation(); - this.ModalServiceSdcUI.openAlertModal('Delete Requirement', - `Are you sure you want to delete requirement: ${req.name}?`, 'OK', () => this.deleteRequirement(req), 'Cancel'); - }; - this.$scope.onDeleteCap = (event: Event, cap: CapabilityUI): void => { - event.stopPropagation(); - this.ModalServiceSdcUI.openAlertModal('Delete Capability', - `Are you sure you want to delete capability: ${cap.name}?`, 'OK', () => this.deleteCapability(cap), 'Cancel'); - }; - this.$scope.onSearchIconClick = (): void => { - this.$scope.filter.show = !!this.$scope.filter.txt || !this.$scope.filter.show; - }; - this.$scope.onFilter = (): void => { - switch (this.$scope.mode) { - case 'requirements': - this.$scope.filteredRequirementsList = _.filter(this.$scope.requirements, req => req.name.includes(this.$scope.filter.txt)); - break; - case 'capabilities': - this.$scope.filteredCapabilitiesList = _.filter(this.$scope.capabilities, cap => cap.name.includes(this.$scope.filter.txt)); - break; - } - }; - this.$scope.isListEmpty = (): boolean => { - switch (this.$scope.mode) { - case 'requirements': - return this.$scope.requirements.length === 0; - case 'capabilities': - return this.$scope.capabilities.length === 0; - } - }; - this.$scope.onSwitchTab = (): void => { - this.$scope.mode = this.$scope.mode === 'requirements' ? 'capabilities' : 'requirements'; - this.$scope.filter.txt = ''; - this.$scope.filter.show = false; - this.$scope.filteredRequirementsList = this.$scope.requirements; - this.$scope.filteredCapabilitiesList = this.$scope.capabilities; - }; - this.$scope.cutToscaTypePrefix = (valToCut: string, textToStartCut: string): string => { - let index = valToCut.indexOf(textToStartCut); - return index !== -1 ? valToCut.substr(index + textToStartCut.length) : valToCut; - }; - }; - - private getIsEditableByComponentType() { - if (this.$scope.componentType === ComponentType.SERVICE) { - return true; - } - if (this.$scope.component.isResource()) { - let componentAsResource: Resource = this.$scope.component; - return componentAsResource.resourceType === ResourceType.VF || - componentAsResource.resourceType === ResourceType.PNF; - } - return false; - }; - - private fetchCapabilitiesRelatedData() { - if (this.$scope.isEditable) { - this.$scope.capabilityTypesList = []; - this.ToscaTypesServiceNg2.fetchCapabilityTypes().subscribe((result: CapabilityTypesMap) => { - _.forEach(result, capabilityType => this.$scope.capabilityTypesList.push(capabilityType)); - }); - this.$scope.nodeTypesList = []; - this.ToscaTypesServiceNg2.fetchNodeTypes().subscribe((result: NodeTypesMap) => { - _.forEach(result, nodeType => this.$scope.nodeTypesList.push(nodeType)); - }); - this.$scope.relationshipTypesList = []; - this.ToscaTypesServiceNg2.fetchRelationshipTypes().subscribe((result: RelationshipTypesMap) => { - _.forEach(result, relshipType => this.$scope.relationshipTypesList.push(relshipType)); - }); - } - } - - private openRequirementsModal(req?: RequirementUI) { - let modalConfig: IModalConfig = { - size: 'md', - title: (req ? 'Update' : 'Add') + ' Requirement', - type: 'custom', - buttons: [ - { - id: 'saveButton', - text: (req ? 'Update' : 'Create'), - size: "'x-small'", - callback: () => this.createOrUpdateRequirement(), - closeModal: true - }, - {text: "Cancel", size: "'x-small'", closeModal: true}] - }; - let modalInputs = { - requirement: req, - relationshipTypesList: this.$scope.relationshipTypesList, - nodeTypesList: this.$scope.nodeTypesList, - capabilityTypesList: this.$scope.capabilityTypesList, - isReadonly: this.$scope.isViewMode() || !this.$scope.isDesigner(), - validityChangedCallback: this.getDisabled - }; - - this.ModalServiceSdcUI.openCustomModal(modalConfig, RequirementsEditorComponent, {input: modalInputs}); - } - - private openCapabilitiesModal(cap?: CapabilityUI) { - let modalConfig: IModalConfig = { - size: 'md', - title: (cap ? 'Update' : 'Add') + ' Capability', - type: 'custom', - buttons: [ - { - id: 'saveButton', - text: (cap ? 'Update' : 'Create'), - size: "'x-small'", - callback: () => this.createOrUpdateCapability(), - closeModal: true - }, - {text: "Cancel", size: "'x-small'", closeModal: true}] - }; - let modalInputs = { - capability: cap, - capabilityTypesList: this.$scope.capabilityTypesList, - isReadonly: this.$scope.isViewMode() || !this.$scope.isDesigner(), - validityChangedCallback: this.getDisabled - }; - - this.ModalServiceSdcUI.openCustomModal(modalConfig, CapabilitiesEditorComponent, {input: modalInputs}); - } - - getDisabled = (shouldEnable: boolean): void => { - let saveButton: ModalButtonComponent = this.ModalServiceSdcUI.getCurrentInstance().getButtonById('saveButton'); - saveButton.disabled = this.$scope.isViewMode() || !this.$scope.isDesigner() || !shouldEnable; - }; - - private createOrUpdateRequirement() { - let requirement = this.ModalServiceSdcUI.getCurrentInstance().innerModalContent.instance.requirementData; - this.$scope.isLoading = true; - if (!requirement.uniqueId) { - this.ComponentServiceNg2.createRequirement(this.$scope.component, requirement).subscribe(result => { - this.$scope.requirements.unshift(new RequirementUI(result[0], this.$scope.component.uniqueId)); - this.$scope.isLoading = false; - }, () => { - this.$scope.isLoading = false; - }); - } - else { - this.ComponentServiceNg2.updateRequirement(this.$scope.component, requirement).subscribe(result => { - let index = this.$scope.requirements.findIndex(req => result[0].uniqueId === req.uniqueId); - this.$scope.requirements[index] = new RequirementUI(result[0], this.$scope.component.uniqueId); - this.$scope.isLoading = false; - this.$scope.$apply(); - }, () => { - this.$scope.isLoading = false; - }); - } - } - - private createOrUpdateCapability() { - let capability = this.ModalServiceSdcUI.getCurrentInstance().innerModalContent.instance.capabilityData; - this.$scope.isLoading = true; - if (!capability.uniqueId) { - this.ComponentServiceNg2.createCapability(this.$scope.component, capability).subscribe(result => { - this.$scope.capabilities.unshift(new CapabilityUI(result[0], this.$scope.component.uniqueId)); - this.$scope.isLoading = false; - }, () => { - this.$scope.isLoading = false; - }); - } - else { - this.ComponentServiceNg2.updateCapability(this.$scope.component, capability).subscribe(result => { - let index = this.$scope.capabilities.findIndex(cap => result[0].uniqueId === cap.uniqueId); - this.$scope.capabilities[index] = new CapabilityUI(result[0], this.$scope.component.uniqueId); - this.$scope.isLoading = false; - this.$scope.$apply(); - }, () => { - this.$scope.isLoading = false; - }); - } - } - - private deleteRequirement(req) { - this.$scope.isLoading = true; - this.ComponentServiceNg2.deleteRequirement(this.$scope.component, req.uniqueId).subscribe(() => { - this.ComponentServiceNg2.getCapabilitiesAndRequirements(this.$scope.componentType, this.$scope.component.uniqueId).subscribe(response => { - this.$scope.component.requirements = response.requirements; - this.initScope('requirements'); - this.$scope.isLoading = false; - }, () => { - this.$scope.isLoading = false; - }); - }, () => { - this.$scope.isLoading = false; - }); - } - - private deleteCapability(cap) { - this.$scope.isLoading = true; - this.ComponentServiceNg2.deleteCapability(this.$scope.component, cap.uniqueId).subscribe(() => { - this.ComponentServiceNg2.getCapabilitiesAndRequirements(this.$scope.componentType, this.$scope.component.uniqueId).subscribe(response => { - this.$scope.component.capabilities = response.capabilities; - this.initScope('capabilities'); - this.$scope.isLoading = false; - }, () => { - this.$scope.isLoading = false; - }); - }, () => { - this.$scope.isLoading = false; - }); - } -} - diff --git a/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view.html b/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view.html deleted file mode 100644 index c661afe0ba..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view.html +++ /dev/null @@ -1,159 +0,0 @@ - - -
    -
    - - -
    -
    - - -
    - -
    -
    -
    -
    {{header.title}} - -
    -
    - -
    - -
    - There are no requirements to display - -
    -
    - -
    - {{req.name}} -
    -
    - {{req.capability.substring("tosca.capabilities.".length)}} -
    -
    - {{req.node.substring("tosca.nodes.".length)}} -
    -
    - {{req.relationship.substring("tosca.relationships.".length)}} -
    -
    -
    - {{req.minOccurrences}},{{req.maxOccurrences}} -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    {{header.title}} - -
    -
    - -
    - -
    - There are no capabilities to display - -
    -
    - -
    - - {{capability.name}} -
    -
    - {{capability.type.replace("tosca.capabilities.","")}} -
    - -
    - {{capability.description}} -
    - -
    - {{capability.validSourceTypes.join(',')}} -
    - -
    - {{capability.minOccurrences}},{{capability.maxOccurrences}} -
    -
    -
    -

    Properties

    -
    -
    -
    -
    {{header.title}} - -
    -
    - -
    -
    - There are no properties to display -
    -
    - - - -
    -
    -
    -
    -
    - -
    -
    -
    - -
    -
    -
    -
    -
    - -
    -
    -
    - diff --git a/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities.less b/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities.less deleted file mode 100644 index 928f6719c6..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities.less +++ /dev/null @@ -1,418 +0,0 @@ -.workspace-req-and-cap { - - width: 93%; - display: inline-block; - - .tabs{ - float: left; - position: relative; - top: 6px; - button{ - float: left; - width: 233px; - height: 38px; - background-color: @tlv_color_t; - border: 1px solid @main_color_o; - color: black; - &:nth-child(1){ - border-radius: 10px 0 0 0; - } - &:nth-child(2){ - border-radius: 0 10px 0 0; - } - &.selected{ - background-color: @main_color_a; - border: 1px solid @main_color_a; - color: white; - } - } - } - .search{ - margin-bottom: 12px; - float: right; - ::-webkit-input-placeholder { - font-style: italic; - } - :-moz-placeholder { - font-style: italic; - } - ::-moz-placeholder { - font-style: italic; - } - :-ms-input-placeholder { - font-style: italic; - } - #search-box{ - -webkit-border-radius: 2px 0 0 2px; - -moz-border-radius: 2px 0 0 2px; - border-radius: 2px 0 0 2px; - width: 213px; - height: 32px; - line-height: 32px; - border: 1px solid @main_color_o; - text-indent: 10px; - float: left; - } - .search-icon-container{ - background-color: @main_color_a; - height: 32px; - width: 32px; - border-radius: 0 2px 2px 0; - float: left; - .search-icon{ - position: relative; - top: 9px; - } - } - } - .add-button { - color: @main_color_a; - } - .add-button, .expand-collapse-buttons { - float: right; - margin-left: 11px; - margin-top: 10px; - &, span { - .hand; - } - } - - - - .table{ - height:490px; - margin-bottom: 0; - } - - .arrow-up-small{ - &.opened{ - .arrow-up-small-hover; - } - } - - .item-opened{ - background-color: @tlv_color_t; - } - - .properties-title{ - margin:0; - font-weight: bold; - } - - .table-container-flex { - margin-top: 10px; - - .text{ - overflow: hidden; - text-overflow: ellipsis; - display: inline-block; - white-space: nowrap; - } - - .editable-table-data { - max-height: 430px; - } - - .data-row { - &:not(.editable-row) { - background: @tlv_color_t; - color: @main_color_n; - } - &.editable-row { - cursor: pointer; - } - .sprite-new.delete-icon { - visibility: hidden; - } - &:hover { - .sprite-new.delete-icon { - visibility: visible; - } - } - } - - &.requirements-table{ - border-top: 4px solid @main_color_a; - .flex-item:nth-child(1) { - flex-grow: 20; - } - - .flex-item:nth-child(2) { - flex-grow: 20; - } - - .flex-item:nth-child(3) { - flex-grow: 20; - } - - .flex-item:nth-child(4) { - flex-grow: 20; - } - - .flex-item:nth-child(5) { - flex-grow: 20; - } - - .flex-item:nth-child(6) { - flex-grow: 20; - } - } - - &.capabilities-table{ - border-top: 4px solid @main_color_a; - .selected{ - .flex-item:nth-child(1) { - border-left: 4px solid @main_color_a; - padding-right: 11px; - } - } - .flex-item:nth-child(1) { - flex-grow: 10; - } - - .flex-item:nth-child(2) { - flex-grow: 10; - } - - .flex-item:nth-child(3) { - flex-grow: 10; - } - - .flex-item:nth-child(4) { - flex-grow: 10; - } - - .flex-item:nth-child(5) { - flex-grow: 10; - } - - } - - &.properties-table{ - .table{ - height: auto; - } - - .flex-item:nth-child(1) { - flex-grow: 15; - a{ - .hand - } - } - - .flex-item:nth-child(2) { - flex-grow: 6; - } - - .flex-item:nth-child(3) { - flex-grow: 6; - } - - .flex-item:nth-child(4) { - flex-grow: 20; - - } - } - - } - -} - -.workspace-req-and-cap-editable { - .tabs-header { - display: flex; - justify-content: space-between; - border-bottom: 1px solid @main_color_o; - .req-and-cap-tabs { - display: flex; - .tab { - font-family: @font-opensans-regular; - font-size: 22px; - padding: 5px; - .hand; - &:first-of-type { - margin-right: 35px; - } - &.selected { - color: @main_color_a; - border-bottom: 2px solid @main_color_a; - } - } - } - .buttons-in-right { - display: flex; - .search { - display: flex; - height: min-content; - margin-top: 10px; - padding-right: 11px; - border-right: 1px solid @main_color_o; - #search-box { - border: none; - border-bottom: 1px solid @main_color_o; - text-indent: 10px; - &:focus { - outline: none; - } - } - .search-icon-container { - margin-top: 3px; - padding-top: 4px; - } - - } - .add-button-icon-and-label { - font-size: 14px; - margin-left: 11px; - margin-top: 10px; - padding-top: 5px; - /deep/ svg-icon { - vertical-align: bottom; - } - &:hover { - &:not(.disabled) { - cursor: pointer; - color: @sdcui_color_light-blue; - } - } - } - } - } - .add-button-icon-and-label { - .icon-label-txt { - text-transform: uppercase; - font-family: @font-opensans-medium; - color: @main_color_a; - &:hover { - &:not(.disabled) { - color: @sdcui_color_light-blue; - } - } - } - } - .empty-list-container { - width: 100%; - display: flex; - justify-content: center; - - .empty-list-add-btn { - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - border: 1px solid @main_color_o; - margin-top: 50px; - height: 229px; - width: 480px; - &.disabled { - pointer-events: none; - } - &:hover { - &:not(.disabled) { - border: 1px solid @main_color_a; - cursor: pointer; - } - } - .icon-label-txt { - margin-top: 15px; - font-size: 16px; - } - } - } - .table-container-flex .table { - .head .head-row { - text-align: left; - &.description { - flex: 2; - } - &.other { - flex: 0.25; - text-align: center; - } - &.occurrences { - flex: 0.75; - } - } - .body .data-row { - border-bottom: none; - border-top: @main_color_o solid 1px; - .ellipsis-text { - overflow: hidden; - text-overflow: ellipsis; - } - &:not(.editable-row) { - background-color: @tlv_color_t; - cursor: default; - color: @main_color_n; - } - &.editable-row { - cursor: pointer; - .table-col-general:hover { - color: @main_color_b; - } - } - &.selected { - background-color: @tlv_color_v; - .name-col { - color: @main_color_a; - } - .sprite-new.arrow-up-small { - background-position: -858px -137px; - margin-bottom: 2px; - } - } - .description-col { - flex: 2; - } - .occurrences-col { - flex: 0.75; - } - .other-col { - display: flex; - justify-content: center; - align-items: center; - flex: 0.25; - .trash-icon { - visibility: hidden; - } - } - &:hover { - .trash-icon { - visibility: visible; - } - } - .multiline-ellipsis { - line-height: 1.5em; - padding: 1px 0 1px 0; - /deep/ .ellipsis-directive-more-less { - float: none; - margin-left: 5px; - color: @main_color_a; - } - } - } - } - - .item-opened.properties-section { - border: 4px solid @tlv_color_v !important; - max-height: 263px; - overflow: auto; - .properties-title { - .s_10; - margin-top: 10px; - } - .properties-table { - &.table-container-flex { - margin-top: 18px; - } - .table { - .head { - border-bottom: 1px solid @main_color_o; - } - .head, .table-col-general { - background-color: @main_color_p; - } - } - } - } -} \ No newline at end of file diff --git a/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts deleted file mode 100644 index a1f8152cea..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts +++ /dev/null @@ -1,105 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -'use strict'; -import * as _ from "lodash"; -import {ArtifactModel, IFileDownload} from "app/models"; -import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model"; -import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response"; -import {ComponentServiceNg2} from "../../../../ng2/services/component-services/component.service"; - -export interface IToscaArtifactsScope extends IWorkspaceViewModelScope { - artifacts:Array; - tableHeadersList:Array; - artifactType:string; - downloadFile:IFileDownload; - isLoading:boolean; - sortBy:string; - reverse:boolean; - - getTitle():string; - download(artifact:ArtifactModel):void; - sort(sortBy:string):void; - showNoArtifactMessage():boolean; -} - -export class ToscaArtifactsViewModel { - - static '$inject' = [ - '$scope', - '$filter', - 'ComponentServiceNg2' - ]; - - constructor(private $scope:IToscaArtifactsScope, - private $filter:ng.IFilterService, - private ComponentServiceNg2:ComponentServiceNg2) { - this.initToscaArtifacts(); - } - - private initToscaArtifacts = (): void => { - - if(!this.$scope.component.toscaArtifacts) { - this.$scope.isLoading = true; - this.ComponentServiceNg2.getComponentToscaArtifacts(this.$scope.component).subscribe((response:ComponentGenericResponse) => { - this.$scope.component.toscaArtifacts = response.toscaArtifacts; - this.initScope(); - this.$scope.isLoading = false; - }, () => { - this.$scope.isLoading = false; - }); - } else { - this.initScope(); - } - } - - private initScope = ():void => { - this.$scope.isLoading = false; - this.$scope.sortBy = 'artifactDisplayName'; - this.$scope.reverse = false; - this.$scope.setValidState(true); - this.$scope.artifactType = 'informational'; - this.$scope.getTitle = ():string => { - return this.$filter("resourceName")(this.$scope.component.name) + ' Artifacts'; - - }; - - this.$scope.tableHeadersList = [ - {title: 'Name', property: 'artifactDisplayName'}, - {title: 'Type', property: 'artifactType'}, - {title: 'Version', property: 'artifactVersion'} - ]; - - this.$scope.artifacts = _.values(this.$scope.component.toscaArtifacts); - this.$scope.sort = (sortBy:string):void => { - this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false; - this.$scope.sortBy = sortBy; - }; - - - this.$scope.showNoArtifactMessage = ():boolean => { - if (this.$scope.artifacts.length === 0) { - return true; - } - return false; - }; - - } -} diff --git a/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view.html b/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view.html deleted file mode 100644 index b354e7a544..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view.html +++ /dev/null @@ -1,65 +0,0 @@ - - -
    -
    -
    -
    -
    {{header.title}} - -
    -
    -
    -
    - -
    - There are no TOSCA artifacts to display -
    -
    - -
    - - {{artifact.artifactDisplayName}} -
    - -
    - {{artifact.artifactType}} -
    - -
    - {{artifact.artifactVersion}} -
    - -
    - -
    -
    -
    -
    Label: {{artifact.artifactLabel}}
    -
    UUID: {{artifact.artifactUUID}}
    -
    Description: {{artifact.description}}
    - - -
    - -
    -
    -
    -
    -
    diff --git a/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less b/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less deleted file mode 100644 index 23be3c3548..0000000000 --- a/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less +++ /dev/null @@ -1,77 +0,0 @@ -.workspace-tosca-artifact { - width: 100%; - display: inline-block; - .w-sdc-classic-btn { - float: right; - margin-bottom: 10px; - } - - .details-title{ - font-weight: bold; - margin-right: 5px; - } - - .table{ - height: 490px; - margin-bottom: 0; - } - - - .table-container-flex { - margin-top: 0; - .item-opened{ - word-wrap: break-word; - } - - - .flex-item:nth-child(1) { - flex-grow: 15; - .hand; - span.table-arrow { - margin-right: 7px; - } - } - - .flex-item:nth-child(2) { - flex-grow: 6; - } - - .flex-item:nth-child(3) { - flex-grow: 1; - } - - .flex-item:nth-child(4) { - flex-grow: 1; - } - - - - - .table-download-btn{ - &.tosca{ - margin-left: 0; - margin-top: 8px; - } - } - - .download-icon-container{ - position: relative; - - .loader{ - left: 60%; - top: 45px; - border: none; - background-color: transparent; - height: 0px; - width: 63px; - outline: none; - - } - } - - - } - -} - - diff --git a/catalog-ui/src/app/view-models/workspace/workspace-view-model.ts b/catalog-ui/src/app/view-models/workspace/workspace-view-model.ts index f4bbed2c96..11667283b2 100644 --- a/catalog-ui/src/app/view-models/workspace/workspace-view-model.ts +++ b/catalog-ui/src/app/view-models/workspace/workspace-view-model.ts @@ -22,103 +22,110 @@ * Created by obarda on 3/30/2016. */ 'use strict'; -import * as _ from "lodash"; +import * as _ from 'lodash'; import { - IUserProperties, IAppMenu, Resource, Component, Plugin, PluginsConfiguration, PluginDisplayOptions, - RelationshipTypeModel, NodeTypeModel, CapabilityTypeModel -} from "app/models"; + IUserProperties, + IAppMenu, + Resource, + Component, + Plugin, + PluginsConfiguration, + PluginDisplayOptions +} from 'app/models'; import { - WorkspaceMode, ComponentFactory, ChangeLifecycleStateHandler, Role, ComponentState, MenuItemGroup, MenuHandler, - MenuItem, ModalsHandler, States, EVENTS, CHANGE_COMPONENT_CSAR_VERSION_FLAG, ResourceType, PREVIOUS_CSAR_COMPONENT -} from "app/utils"; + MenuItem, ModalsHandler, States, EVENTS, CHANGE_COMPONENT_CSAR_VERSION_FLAG, ResourceType, PREVIOUS_CSAR_COMPONENT, + WorkspaceMode, ComponentFactory, ChangeLifecycleStateHandler, Role, ComponentState, MenuItemGroup, MenuHandler +} from 'app/utils'; import { EventListenerService, - EntityService, - ProgressService, - CacheService, - LeftPaletteLoaderService -} from "app/services"; -import {FileUploadModel} from "../../directives/file-upload/file-upload"; -import {AutomatedUpgradeService} from "../../ng2/pages/automated-upgrade/automated-upgrade.service"; -import {ComponentServiceNg2} from "../../ng2/services/component-services/component.service"; -import {EventBusService} from "../../ng2/services/event-bus.service"; -import {PluginsService} from "../../ng2/services/plugins.service"; -import {IDependenciesServerResponse} from "../../ng2/services/responses/dependencies-server-response"; + LeftPaletteLoaderService, + ProgressService +} from 'app/services'; +import { + CacheService +} from 'app/services-ng2'; +import { AutomatedUpgradeService } from '../../ng2/pages/automated-upgrade/automated-upgrade.service'; +import { CatalogService } from '../../ng2/services/catalog.service'; +import { ComponentServiceNg2 } from '../../ng2/services/component-services/component.service'; +import { EventBusService } from '../../ng2/services/event-bus.service'; +import { HomeService } from '../../ng2/services/home.service'; +import { PluginsService } from '../../ng2/services/plugins.service'; +import { IDependenciesServerResponse } from '../../ng2/services/responses/dependencies-server-response'; +import { WorkspaceNg1BridgeService } from '../../ng2/pages/workspace/workspace-ng1-bridge-service'; +import { WorkspaceService } from '../../ng2/pages/workspace/workspace.service'; export interface IWorkspaceViewModelScope extends ng.IScope { - isLoading:boolean; - isCreateProgress:boolean; - component:Component; - originComponent:Component; - componentType:string; - importFile:any; - leftBarTabs:MenuItemGroup; - isNew:boolean; - isFromImport:boolean; - isValidForm:boolean; - isActiveTopBar:boolean; - mode:WorkspaceMode; - breadcrumbsModel:Array; - sdcMenu:IAppMenu; - changeLifecycleStateButtons:any; - version:string; - versionsList:Array; - changeVersion:any; - isComposition:boolean; - isDeployment:boolean; - isPlugins:boolean; - $state:ng.ui.IStateService; - user:IUserProperties; - thirdParty:boolean; - disabledButtons:boolean; - menuComponentTitle:string; - progressService:ProgressService; - progressMessage:string; + isLoading: boolean; + isCreateProgress: boolean; + component: Component; + originComponent: Component; + componentType: string; + importFile: any; + leftBarTabs: MenuItemGroup; + isNew: boolean; + isFromImport: boolean; + isValidForm: boolean; + isActiveTopBar: boolean; + mode: WorkspaceMode; + breadcrumbsModel: Array; + sdcMenu: IAppMenu; + changeLifecycleStateButtons: any; + version: string; + versionsList: Array; + changeVersion: any; + isComposition: boolean; + isDeployment: boolean; + isPlugins: boolean; + $state: ng.ui.IStateService; + user: IUserProperties; + thirdParty: boolean; + disabledButtons: boolean; + menuComponentTitle: string; + progressService: ProgressService; + progressMessage: string; ComponentServiceNg2: ComponentServiceNg2; // leftPanelComponents:Array; //this is in order to load the left panel once, and not wait long time when moving to composition - unsavedChanges:boolean; - unsavedChangesCallback:Function; - unsavedFile:boolean; - capabilityTypesList: Array; - relationshipTypesList: Array; - nodeTypesList: Array; - - - startProgress(message:string):void; - stopProgress():void; - updateBreadcrumbs(component:Component):void; - updateUnsavedFileFlag(isUnsaved:boolean):void; - showChangeStateButton():boolean; - getComponent():Component; - setComponent(component:Component):void; - setOriginComponent(component:Component):void; - onMenuItemPressed(state:string, params:any):ng.IPromise; - create():void; - save():Promise; - setValidState(isValid:boolean):void; - changeLifecycleState(state:string):void; - handleChangeLifecycleState(state:string, newCsarVersion?:string):void; - disableMenuItems():void; - enableMenuItems():void; - isDesigner():boolean; - isViewMode():boolean; - isEditMode():boolean; - isCreateMode():boolean; - isDisableMode():boolean; - isGeneralView():boolean; - goToBreadcrumbHome():void; - onVersionChanged(selectedId:string):void; - getLatestVersion():void; - getStatus():string; - showLifecycleIcon():boolean; - updateSelectedMenuItem(state:string):void; - isSelected(menuItem:MenuItem):boolean; - uploadFileChangedInGeneralTab():void; - updateMenuComponentName(ComponentName:string):void; - getTabTitle():string; - reload(component:Component):void; + unsavedChanges: boolean; + unsavedChangesCallback: Function; + unsavedFile: boolean; + hasNoDependencies: boolean; + + + startProgress(message: string): void; + stopProgress(): void; + updateBreadcrumbs(component: Component): void; + updateUnsavedFileFlag(isUnsaved: boolean): void; + showChangeStateButton(): boolean; + getComponent(): Component; + setComponent(component: Component): void; + setOriginComponent(component: Component): void; + onMenuItemPressed(state: string, params: any): ng.IPromise; + create(): void; + save(): Promise; + setValidState(isValid: boolean): void; + changeLifecycleState(state: string): void; + handleChangeLifecycleState(state: string, newCsarVersion?: string, errorFunction?: Function): void; + disableMenuItems(): void; + enableMenuItems(): void; + isDesigner(): boolean; + isViewMode(): boolean; + isEditMode(): boolean; + isCreateMode(): boolean; + isDisableMode(): boolean; + isGeneralView(): boolean; + goToBreadcrumbHome(): void; + onVersionChanged(selectedId: string): void; + getLatestVersion(): void; + getStatus(): string; + showLifecycleIcon(): boolean; + updateSelectedMenuItem(state: string): void; + isSelected(menuItem: MenuItem): boolean; + uploadFileChangedInGeneralTab(): void; + updateMenuComponentName(ComponentName: string): void; + getTabTitle(): string; + reload(component: Component): void; } export class WorkspaceViewModel { @@ -133,53 +140,55 @@ export class WorkspaceViewModel { 'MenuHandler', 'Sdc.Services.CacheService', 'ChangeLifecycleStateHandler', - 'ModalsHandler', 'LeftPaletteLoaderService', '$filter', 'EventListenerService', - 'Sdc.Services.EntityService', 'Notification', '$stateParams', + 'HomeService', + 'CatalogService', 'Sdc.Services.ProgressService', 'ComponentServiceNg2', 'AutomatedUpgradeService', 'EventBusService', - 'PluginsService' + 'PluginsService', + 'WorkspaceNg1BridgeService', + 'workspaceService' ]; - constructor(private $scope:IWorkspaceViewModelScope, - private injectComponent:Component, - private ComponentFactory:ComponentFactory, - private $state:ng.ui.IStateService, - private sdcMenu:IAppMenu, - private $q:ng.IQService, - private MenuHandler:MenuHandler, - private cacheService:CacheService, - private ChangeLifecycleStateHandler:ChangeLifecycleStateHandler, - private ModalsHandler:ModalsHandler, - private LeftPaletteLoaderService:LeftPaletteLoaderService, - private $filter:ng.IFilterService, - private EventListenerService:EventListenerService, - private EntityService:EntityService, - private Notification:any, - private $stateParams:any, - private progressService:ProgressService, - private ComponentServiceNg2:ComponentServiceNg2, - private AutomatedUpgradeService:AutomatedUpgradeService, - private eventBusService:EventBusService, - private pluginsService:PluginsService) { - - - - this.initScope(); - this.initAfterScope(); - this.$scope.updateSelectedMenuItem(this.$state.current.name); + constructor(private $scope: IWorkspaceViewModelScope, + private injectComponent: Component, + private ComponentFactory: ComponentFactory, + private $state: ng.ui.IStateService, + private sdcMenu: IAppMenu, + private $q: ng.IQService, + private MenuHandler: MenuHandler, + private cacheService: CacheService, + private ChangeLifecycleStateHandler: ChangeLifecycleStateHandler, + private LeftPaletteLoaderService: LeftPaletteLoaderService, + private $filter: ng.IFilterService, + private EventListenerService: EventListenerService, + private Notification: any, + private $stateParams: any, + private homeService: HomeService, + private catalogService: CatalogService, + private progressService: ProgressService, + private ComponentServiceNg2: ComponentServiceNg2, + private AutomatedUpgradeService: AutomatedUpgradeService, + private eventBusService: EventBusService, + private pluginsService: PluginsService, + private workspaceNg1BridgeService: WorkspaceNg1BridgeService, + private workspaceService: WorkspaceService) { + + this.initScope(); + // this.initAfterScope(); + this.$scope.updateSelectedMenuItem(this.$state.current.name); } - private role:string; - private category:string; - private components:Array; - + private role: string; + private category: string; + private components: Component[]; + private initViewMode = ():WorkspaceMode => { let mode = WorkspaceMode.VIEW; @@ -187,35 +196,34 @@ export class WorkspaceViewModel { mode = WorkspaceMode.CREATE; } else { if (this.$scope.component.lifecycleState === ComponentState.NOT_CERTIFIED_CHECKOUT && - this.$scope.component.lastUpdaterUserId === this.cacheService.get("user").userId) { - if ((this.$scope.component.isService() || this.$scope.component.isResource()) && this.role == Role.DESIGNER) { + this.$scope.component.lastUpdaterUserId === this.cacheService.get('user').userId) { + if ((this.$scope.component.isService() || this.$scope.component.isResource()) && this.role === Role.DESIGNER) { mode = WorkspaceMode.EDIT; } } } + this.workspaceNg1BridgeService.updateIsViewOnly(mode === WorkspaceMode.VIEW); return mode; - }; + } - private initChangeLifecycleStateButtons = ():void => { - let state = this.$scope.component.isService() && (Role.OPS == this.role || Role.GOVERNOR == this.role) ? this.$scope.component.distributionStatus : this.$scope.component.lifecycleState; + private initChangeLifecycleStateButtons = (): void => { + let state: string; + if (this.$scope.component.isService() && this.$scope.component.lifecycleState === 'CERTIFIED') { + state = this.$scope.component.distributionStatus; + } else { + state = this.$scope.component.lifecycleState; + } this.$scope.changeLifecycleStateButtons = (this.sdcMenu.roles[this.role].changeLifecycleStateButtons[state] || [])[this.$scope.component.componentType.toUpperCase()]; + } - }; - - private initLeftPalette = ():void => { - //this.LeftPaletteLoaderService.loadLeftPanel(this.$scope.component); - }; - - private initScope = ():void => { - + private initScope = (): void => { this.$scope.component = this.injectComponent; - //this.initLeftPalette(); this.$scope.menuComponentTitle = this.$scope.component.name; this.$scope.disabledButtons = false; this.$scope.originComponent = this.ComponentFactory.createComponent(this.$scope.component); this.$scope.componentType = this.$scope.component.componentType; this.$scope.version = this.cacheService.get('version'); - this.$scope.user = this.cacheService.get("user"); + this.$scope.user = this.cacheService.get('user'); this.role = this.$scope.user.role; this.category = this.$scope.component.selectedCategory; this.$scope.mode = this.initViewMode(); @@ -229,10 +237,11 @@ export class WorkspaceViewModel { this.$scope.progressService = this.progressService; this.$scope.unsavedChanges = false; - this.EventListenerService.registerObserverCallback(EVENTS.ON_WORKSPACE_UNSAVED_CHANGES, this.setWorkspaceButtonState); - //this.EventListenerService.registerObserverCallback(EVENTS.ON_UPDATE_VSP_FILE, this.updateVspFlag); + this.$scope.hasNoDependencies = true; + this.verifyIfDependenciesExist(); - this.$scope.getComponent = ():Component => { + this.EventListenerService.registerObserverCallback(EVENTS.ON_WORKSPACE_UNSAVED_CHANGES, this.setWorkspaceButtonState); + this.$scope.getComponent = (): Component => { return this.$scope.component; }; @@ -261,17 +270,17 @@ export class WorkspaceViewModel { this.$scope.archiveComponent = ():void => { this.$scope.isLoading = true; const typeComponent = this.$scope.component.componentType; - this.ComponentServiceNg2.archiveComponent(typeComponent, this.$scope.component.uniqueId).subscribe(()=>{ + this.ComponentServiceNg2.archiveComponent(typeComponent, this.$scope.component.uniqueId).subscribe(()=> { this.$scope.isLoading = false; - if(this.$state.params.previousState){ - switch(this.$state.params.previousState){ + if (this.$state.params.previousState) { + switch (this.$state.params.previousState) { case 'catalog': case 'dashboard': this.$state.go(this.$state.params.previousState); break; default: break; - } + } } this.$scope.component.archived = true; this.deleteArchiveCache(); @@ -281,17 +290,17 @@ export class WorkspaceViewModel { title: this.$filter('translate')("ARCHIVE_SUCCESS_MESSAGE_TITLE") }); }, (error) => { this.$scope.isLoading = false; }); - } + } this.$scope.restoreComponent = ():void => { this.$scope.isLoading = true; const typeComponent = this.$scope.component.componentType; - this.ComponentServiceNg2.restoreComponent(typeComponent, this.$scope.component.uniqueId).subscribe(()=>{ + this.ComponentServiceNg2.restoreComponent(typeComponent, this.$scope.component.uniqueId).subscribe(()=> { this.$scope.isLoading = false; this.Notification.success({ - message: this.$scope.component.name + ' ' + this.$filter('translate')("RESTORE_SUCCESS_MESSAGE_TEXT"), - title: this.$filter('translate')("RESTORE_SUCCESS_MESSAGE_TITLE") - }); + message: this.$scope.component.name + ' ' + this.$filter('translate')("RESTORE_SUCCESS_MESSAGE_TEXT"), + title: this.$filter('translate')("RESTORE_SUCCESS_MESSAGE_TITLE") + }); }); this.$scope.component.archived = false; this.deleteArchiveCache(); @@ -304,13 +313,13 @@ export class WorkspaceViewModel { if(this.$scope.isValidForm){ this.$scope.save().then(() => { this.$scope.onMenuItemPressed(toState.name, toParams); - }, ()=> { + }, ()=> { console.error("Save failed, unable to navigate to " + toState.name); }) } else { console.error("Form is invalid, unable to navigate to " + toState.name); } - } + } } }); @@ -384,7 +393,7 @@ export class WorkspaceViewModel { }; this.$scope.create = () => { - + this.$scope.startProgress("Creating Asset..."); _.first(this.$scope.leftBarTabs.menuItems).isDisabled = true;//disabled click on general tab (DE246274) @@ -429,7 +438,7 @@ export class WorkspaceViewModel { }; this.$scope.save = ():Promise => { - + this.EventListenerService.notifyObservers(EVENTS.ON_WORKSPACE_SAVE_BUTTON_CLICK); this.$scope.startProgress("Updating Asset..."); @@ -445,6 +454,7 @@ export class WorkspaceViewModel { let onFailed = () => { stopProgressAndEnableUI(); + this.$scope.updateUnsavedFileFlag(true); this.EventListenerService.notifyObservers(EVENTS.ON_WORKSPACE_SAVE_BUTTON_ERROR); reject(); @@ -459,7 +469,7 @@ export class WorkspaceViewModel { }); this.$scope.updateBreadcrumbs(component); - + //update the component this.$scope.setComponent(component); this.$scope.originComponent = this.ComponentFactory.createComponent(this.$scope.component); @@ -467,13 +477,14 @@ export class WorkspaceViewModel { if (this.cacheService.contains(CHANGE_COMPONENT_CSAR_VERSION_FLAG)) { this.cacheService.remove(CHANGE_COMPONENT_CSAR_VERSION_FLAG); } - if (this.cacheService.contains(PREVIOUS_CSAR_COMPONENT)){ + if (this.cacheService.contains(PREVIOUS_CSAR_COMPONENT)) { this.cacheService.remove(PREVIOUS_CSAR_COMPONENT); } //clear edit flags this.$state.current.data.unsavedChanges = false; this.$scope.unsavedFile = false; + this.$scope.reload(component); resolve(); }; @@ -497,35 +508,40 @@ export class WorkspaceViewModel { this.$state.go('dashboard'); }; - this.$scope.handleChangeLifecycleState = (state:string, newCsarVersion?:string) => { + this.$scope.handleChangeLifecycleState = (state:string, newCsarVersion?:string, onError?: Function) => { if ('monitor' === state) { this.$state.go('workspace.distribution'); return; } let data = this.$scope.changeLifecycleStateButtons[state]; - let onSuccess = (component:Component, url:string):void => { - //Updating the component from server response - + if (!data && this.$stateParams.componentCsar && !this.$scope.isCreateMode()) { + data = {text: 'Check Out', url: 'lifecycleState/CHECKOUT'}; + } + const onSuccess = (component, url:string):void => { + // Updating the component from server response + // Creating the data object to notify the plugins with - let eventData: any = { + const eventData: any = { uuid: this.$scope.component.uuid, version: this.$scope.component.version }; - //the server returns only metaData (small component) except checkout (Full component) ,so we update only the statuses of distribution & lifecycle + // the server returns only metaData (small component) except checkout (Full component) ,so we update only the statuses of distribution & lifecycle this.$scope.component.lifecycleState = component.lifecycleState; this.$scope.component.distributionStatus = component.distributionStatus; switch (url) { case 'lifecycleState/CHECKOUT': + this.workspaceNg1BridgeService.updateIsViewOnly(false); this.eventBusService.notify("CHECK_OUT", eventData, false).subscribe(() => { // only checkOut get the full component from server // this.$scope.component = component; // Work around to change the csar version if(newCsarVersion) { this.cacheService.set(CHANGE_COMPONENT_CSAR_VERSION_FLAG, newCsarVersion); - } + (this.$scope.component as Resource).csarVersion = newCsarVersion; + } //when checking out a minor version uuid remains const bcIdx = _.findIndex(this.components, (item) => { @@ -542,6 +558,7 @@ export class WorkspaceViewModel { this.initVersionObject(); this.$scope.isLoading = false; this.EventListenerService.notifyObservers(EVENTS.ON_CHECKOUT, component); + this.workspaceService.setComponentMetadata(component); this.Notification.success({ message: this.$filter('translate')("CHECKOUT_SUCCESS_MESSAGE_TEXT"), @@ -551,6 +568,7 @@ export class WorkspaceViewModel { }); break; case 'lifecycleState/CHECKIN': + this.workspaceNg1BridgeService.updateIsViewOnly(true); defaultActionAfterChangeLifecycleState(); this.Notification.success({ message: this.$filter('translate')("CHECKIN_SUCCESS_MESSAGE_TEXT"), @@ -566,77 +584,25 @@ export class WorkspaceViewModel { }); }); break; - case 'lifecycleState/certificationRequest': - defaultActionAfterChangeLifecycleState(); - this.Notification.success({ - message: this.$filter('translate')("SUBMIT_FOR_TESTING_SUCCESS_MESSAGE_TEXT"), - title: this.$filter('translate')("SUBMIT_FOR_TESTING_SUCCESS_MESSAGE_TITLE") - }); - break; - //Tester Role - case 'lifecycleState/failCertification': - defaultActionAfterChangeLifecycleState(); - this.Notification.success({ - message: this.$filter('translate')("REJECT_SUCCESS_MESSAGE_TEXT"), - title: this.$filter('translate')("REJECT_SUCCESS_MESSAGE_TITLE") - }); - break; case 'lifecycleState/certify': - this.$scope.handleCertification(component); - + this.verifyIfDependenciesExist(); + this.$scope.reload(component); break; - //DE203504 Bug Fix Start - case 'lifecycleState/startCertification': - this.initChangeLifecycleStateButtons(); - this.Notification.success({ - message: this.$filter('translate')("START_TESTING_SUCCESS_MESSAGE_TEXT"), - title: this.$filter('translate')("START_TESTING_SUCCESS_MESSAGE_TITLE") - }); - break; - case 'lifecycleState/cancelCertification': - this.initChangeLifecycleStateButtons(); - this.Notification.success({ - message: this.$filter('translate')("CANCEL_TESTING_SUCCESS_MESSAGE_TEXT"), - title: this.$filter('translate')("CANCEL_TESTING_SUCCESS_MESSAGE_TITLE") - }); - break; - //Ops Role - case 'distribution/PROD/activate': - this.initChangeLifecycleStateButtons(); + case 'distribution/PROD/activate': this.Notification.success({ message: this.$filter('translate')("DISTRIBUTE_SUCCESS_MESSAGE_TEXT"), title: this.$filter('translate')("DISTRIBUTE_SUCCESS_MESSAGE_TITLE") }); - break; - //Governor Role - case 'distribution-state/reject': this.initChangeLifecycleStateButtons(); - this.Notification.success({ - message: this.$filter('translate')("REJECT_SUCCESS_MESSAGE_TEXT"), - title: this.$filter('translate')("REJECT_SUCCESS_MESSAGE_TITLE") - }); break; - case 'distribution-state/approve': - this.initChangeLifecycleStateButtons(); - this.$state.go('catalog'); - this.Notification.success({ - message: this.$filter('translate')("APPROVE_SUCCESS_MESSAGE_TEXT"), - title: this.$filter('translate')("APPROVE_SUCCESS_MESSAGE_TITLE") - }); - break; - //DE203504 Bug Fix End - default : defaultActionAfterChangeLifecycleState(); - } - if (data.url != 'lifecycleState/CHECKOUT') { + if (data.url !== 'lifecycleState/CHECKOUT') { this.$scope.isLoading = false; } }; - //this.$scope.isLoading = true; - this.ChangeLifecycleStateHandler.changeLifecycleState(this.$scope.component, data, this.$scope, onSuccess); }; @@ -663,6 +629,21 @@ export class WorkspaceViewModel { return this.$scope.mode === WorkspaceMode.CREATE; }; + this.$scope.checkDisableButton = (button: any):boolean => { + // Logic moved from html to component + if (this.$scope.isCreateMode() || button.disabled || this.$scope.disabledButtons || !this.$scope.isValidForm || this.$scope.unsavedChanges || this.$scope.component.archived){ + return true; + } + + // Specific verification for Checkout - enabled only in case the component is the latest version. + let result: boolean = false; + + if (button.url === 'lifecycleState/CHECKOUT') { + result = !this.$scope.component.isLatestVersion(); + } + return result; + }; + this.$scope.isEditMode = ():boolean => { return this.$scope.mode === WorkspaceMode.EDIT; }; @@ -686,18 +667,14 @@ export class WorkspaceViewModel { this.initMenuItems(); - this.$scope.showChangeStateButton = ():boolean => { - let result:boolean = true; - if (!this.$scope.component.isLatestVersion() && Role.OPS != this.role && Role.GOVERNOR != this.role) { + this.$scope.showLatestVersion = (): boolean => { + let result: boolean = true; + if (!this.$scope.component.isLatestVersion()) { result = false; } if (ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState && this.$scope.isViewMode()) { result = false; } - if (ComponentState.CERTIFIED != this.$scope.component.lifecycleState && - (Role.OPS == this.role || Role.GOVERNOR == this.role)) { - result = false; - } return result; }; @@ -705,20 +682,20 @@ export class WorkspaceViewModel { let stateArray:Array = state.split('.', 2); let stateWithoutInternalNavigate:string = stateArray[0] + '.' + stateArray[1]; let selectedItem:MenuItem = _.find(this.$scope.leftBarTabs.menuItems, (item:MenuItem) => { - let itemStateArray: Array = item.state.split('.', 2); + let itemStateArray:Array = item.state.split('.', 2); let itemStateWithoutNavigation:string = itemStateArray[0] + '.' + itemStateArray[1]; return (itemStateWithoutNavigation === stateWithoutInternalNavigate); }); let selectedIndex = selectedItem ? this.$scope.leftBarTabs.menuItems.indexOf(selectedItem) : 0; - if (stateArray[1] === 'plugins') { + if (stateArray[1] === 'plugins') { _.forEach(PluginsConfiguration.plugins, (plugin) => { if (plugin.pluginStateUrl == this.$state.params.path) { return false; } else if (this.pluginsService.isPluginDisplayedInContext(plugin, this.role, this.$scope.component.getComponentSubType())) { - selectedIndex++; + selectedIndex++; } }); } @@ -726,11 +703,11 @@ export class WorkspaceViewModel { this.$scope.leftBarTabs.selectedIndex = selectedIndex; }; - this.$scope.isSelected = (menuItem:MenuItem): boolean => { + this.$scope.isSelected = (menuItem: MenuItem): boolean => { return this.$scope.leftBarTabs.selectedIndex === _.indexOf(this.$scope.leftBarTabs.menuItems, menuItem); }; - this.$scope.$watch('$state.current.name', (newVal:string):void => { + this.$scope.$watch('$state.current.name', (newVal: string): void => { if (newVal) { this.$scope.isComposition = (newVal.indexOf(States.WORKSPACE_COMPOSITION) > -1); this.$scope.isDeployment = newVal == States.WORKSPACE_DEPLOYMENT; @@ -738,20 +715,26 @@ export class WorkspaceViewModel { } }); - this.$scope.getTabTitle = ():string => { - return this.$scope.leftBarTabs.menuItems.find((menuItem:MenuItem) => { + this.$scope.getTabTitle = (): string => { + return this.$scope.leftBarTabs.menuItems.find((menuItem: MenuItem) => { return menuItem.state == this.$scope.$state.current.name; }).text; }; - this.$scope.reload = (component:Component):void => { - this.$state.go(this.$state.current.name, {id: component.uniqueId}, {reload: true}); + this.$scope.reload = (component: Component): void => { + const isGeneralTab = this.$state.current.name === 'workspace.general'; + // nullify the componentCsar in case we are in general tab so we know we didnt came from updateVsp Modal + if (isGeneralTab) { + this.$state.go(this.$state.current.name, {id: component.uniqueId, componentCsar: null}, {reload: true}); + } else { + this.$state.go(this.$state.current.name, {id: component.uniqueId}, {reload: true}); + } }; this.$scope.$on('$destroy', () => { this.EventListenerService.unRegisterObserver(EVENTS.ON_WORKSPACE_UNSAVED_CHANGES); }); - + this.$scope.openAutomatedUpgradeModal = ():void => { this.$scope.isLoading = true; this.ComponentServiceNg2.getDependencies(this.$scope.component.componentType, this.$scope.component.uniqueId).subscribe((response:Array)=> { @@ -761,14 +744,14 @@ export class WorkspaceViewModel { } this.$scope.handleCertification = (certifyComponent): void => { - if (this.$scope.component.getComponentSubType() === ResourceType.VF) { + if (this.$scope.component.getComponentSubType() === ResourceType.VF || this.$scope.component.isService()) { this.ComponentServiceNg2.getDependencies(this.$scope.component.componentType, this.$scope.component.uniqueId).subscribe((response:Array) => { this.$scope.isLoading = false; - let isUpgradeNeeded = _.filter(response, (componentToUpgrade:IDependenciesServerResponse) => { + const isUpgradeNeeded = _.filter(response, (componentToUpgrade:IDependenciesServerResponse) => { return componentToUpgrade.dependencies && componentToUpgrade.dependencies.length > 0; }); - if(isUpgradeNeeded.length === 0) { + if (isUpgradeNeeded.length === 0) { this.onSuccessWithoutUpgradeNeeded(); return; } @@ -781,52 +764,54 @@ export class WorkspaceViewModel { } this.$scope.disableMenuItems = () => { - this.$scope.leftBarTabs.menuItems.forEach((item:MenuItem) => { - item.isDisabled = (States.WORKSPACE_GENERAL != item.state); + this.$scope.leftBarTabs.menuItems.forEach((item: MenuItem) => { + item.isDisabled = (States.WORKSPACE_GENERAL !== item.state); }); } - + this.$scope.enableMenuItems = () => { - this.$scope.leftBarTabs.menuItems.forEach((item:MenuItem) => { + this.$scope.leftBarTabs.menuItems.forEach((item: MenuItem) => { item.isDisabled = false; }); - } + }; - this.$scope.startProgress = (message:string):void => { + this.$scope.startProgress = (message: string): void => { this.progressService.initCreateComponentProgress(this.$scope.component.uniqueId); this.$scope.isCreateProgress = true; this.$scope.progressMessage = message; }; - this.$scope.stopProgress = ():void => { + this.$scope.stopProgress = (): void => { this.$scope.isCreateProgress = false; this.progressService.deleteProgressValue(this.$scope.component.uniqueId); } - this.$scope.updateBreadcrumbs = (component:Component):void => { + this.$scope.updateBreadcrumbs = (component: Component): void => { // Update the components list for breadcrumbs const bcIdx = this.MenuHandler.findBreadcrumbComponentIndex(this.components, component); if (bcIdx !== -1) { this.components[bcIdx] = component; this.initBreadcrumbs(); // re-calculate breadcrumbs } - } + }; this.$scope.updateUnsavedFileFlag = (isUnsaved:boolean) => { this.$scope.unsavedFile = isUnsaved; - } + }; - }; + } - private onSuccessWithoutUpgradeNeeded = ():void => { + private onSuccessWithoutUpgradeNeeded = (): void => { this.$scope.isLoading = false; this.Notification.success({ - message: this.$filter('translate')("ACCEPT_TESTING_SUCCESS_MESSAGE_TEXT"), - title: this.$filter('translate')("ACCEPT_TESTING_SUCCESS_MESSAGE_TITLE") + message: this.$filter('translate')('SERVICE_CERTIFICATION_STATUS_TEXT'), + title: this.$filter('translate')('SERVICE_CERTIFICATION_STATUS_TITLE') }); - this.$state.go('dashboard'); + this.initVersionObject(); + this.initChangeLifecycleStateButtons(); } + private refreshDataAfterChangeLifecycleState = (component:Component):void => { this.$scope.isLoading = false; this.$scope.mode = this.initViewMode(); @@ -835,42 +820,42 @@ export class WorkspaceViewModel { this.EventListenerService.notifyObservers(EVENTS.ON_LIFECYCLE_CHANGE, component); } - private initAfterScope = ():void => { + private initAfterScope = (): void => { // In case user select csar from the onboarding modal, need to disable checkout and submit for testing. if (this.$state.params['disableButtons'] === true) { this.$scope.uploadFileChangedInGeneralTab(); } }; - private initVersionObject = ():void => { + private initVersionObject = (): void => { this.$scope.versionsList = (this.$scope.component.getAllVersionsAsSortedArray()).reverse(); this.$scope.changeVersion = { - selectedVersion: _.find(this.$scope.versionsList, (versionObj)=> { + selectedVersion: _.find(this.$scope.versionsList, (versionObj) => { return versionObj.versionId === this.$scope.component.uniqueId; }) }; - }; + } - private getNewComponentBreadcrumbItem = ():MenuItem => { - let text = ""; + private getNewComponentBreadcrumbItem = (): MenuItem => { + let text = ''; if (this.$scope.component.isResource() && (this.$scope.component).isCsarComponent()) { text = this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name; } else { text = 'Create new ' + this.$state.params['type']; } return new MenuItem(text, null, States.WORKSPACE_GENERAL, 'goToState', [this.$state.params]); - }; + } - private updateMenuItemByRole = (menuItems:Array, role:string) => { - let tempMenuItems:Array = new Array(); - menuItems.forEach((item:any) => { + private updateMenuItemByRole = (menuItems: any[], role: string) => { + const tempMenuItems: any[] = new Array(); + menuItems.forEach((item: any) => { //remove item if role is disabled if (!(item.disabledRoles && item.disabledRoles.indexOf(role) > -1)) { tempMenuItems.push(item); } }); return tempMenuItems; - }; + } private updateMenuItemByCategory = (menuItems:Array, category:string) => { let tempMenuItems:Array = new Array(); @@ -888,15 +873,15 @@ export class WorkspaceViewModel { private deleteArchiveCache = () => { - this.cacheService.remove("archiveComponents"); //delete the cache to ensure the archive is reloaded from server - }; + this.cacheService.remove('archiveComponents'); // delete the cache to ensure the archive is reloaded from server + } private initBreadcrumbs = () => { this.components = this.cacheService.get('breadcrumbsComponents'); - let breadcrumbsComponentsLvl = this.MenuHandler.generateBreadcrumbsModelFromComponents(this.components, this.$scope.component); + const breadcrumbsComponentsLvl = this.MenuHandler.generateBreadcrumbsModelFromComponents(this.components, this.$scope.component); if (this.$scope.isCreateMode()) { - let createItem = this.getNewComponentBreadcrumbItem(); + const createItem = this.getNewComponentBreadcrumbItem(); if (!breadcrumbsComponentsLvl.menuItems) { breadcrumbsComponentsLvl.menuItems = []; } @@ -905,25 +890,23 @@ export class WorkspaceViewModel { } this.$scope.breadcrumbsModel = [breadcrumbsComponentsLvl, this.$scope.leftBarTabs]; - }; + } private initMenuItems() { - let inCreateMode = this.$scope.isCreateMode(); + const inCreateMode = this.$scope.isCreateMode(); this.$scope.leftBarTabs = new MenuItemGroup(); - //const menuItemsObjects:Array = this.updateMenuItemByRole(this.sdcMenu.component_workspace_menu_option[this.$scope.component.getComponentSubType()], this.role); - let menuItemsObjects:Array = this.updateMenuItemByRole(this.sdcMenu.component_workspace_menu_option[this.$scope.component.getComponentSubType()], this.role); - if(this.$scope.component.getComponentSubType()==="SERVICE") - { - let menuItemsObjectsCategory:Array = this.updateMenuItemByCategory(menuItemsObjects, this.category); - menuItemsObjects = menuItemsObjectsCategory; + let menuItemsObjects: any[] = this.updateMenuItemByRole(this.sdcMenu.component_workspace_menu_option[this.$scope.component.getComponentSubType()], this.role); + if (this.$scope.component.getComponentSubType() === 'SERVICE') { + const menuItemsObjectsCategory: any[] = this.updateMenuItemByCategory(menuItemsObjects, this.category); + menuItemsObjects = menuItemsObjectsCategory; } // Only adding plugins to the workspace if they can be displayed for the current user role _.each(PluginsConfiguration.plugins, (plugin: Plugin) => { if (this.pluginsService.isPluginDisplayedInContext(plugin, this.role, this.$scope.component.getComponentSubType())) { menuItemsObjects.push({ - text: plugin.pluginDisplayOptions["context"].displayName, + text: plugin.pluginDisplayOptions['context'].displayName, action: 'onMenuItemPressed', state: 'workspace.plugins', params: {path: plugin.pluginStateUrl} @@ -931,7 +914,7 @@ export class WorkspaceViewModel { } }); - this.$scope.leftBarTabs.menuItems = menuItemsObjects.map((item:MenuItem) => { + this.$scope.leftBarTabs.menuItems = menuItemsObjects.map((item: MenuItem) => { const menuItem = new MenuItem(item.text, item.callback, item.state, item.action, item.params, item.blockedForTypes, item.disabledCategory); if (menuItem.params) { menuItem.params.state = menuItem.state; @@ -940,7 +923,7 @@ export class WorkspaceViewModel { menuItem.params = {state: menuItem.state}; } menuItem.callback = () => this.$scope[menuItem.action](menuItem.state, menuItem.params); - menuItem.isDisabled = (inCreateMode && States.WORKSPACE_GENERAL != menuItem.state) || + menuItem.isDisabled = (inCreateMode && States.WORKSPACE_GENERAL !== menuItem.state) || (States.WORKSPACE_DEPLOYMENT === menuItem.state && this.$scope.component.modules && this.$scope.component.modules.length === 0 && this.$scope.component.isResource()) || (menuItem.disabledCategory === true); @@ -950,20 +933,54 @@ export class WorkspaceViewModel { if (this.cacheService.get('breadcrumbsComponents')) { this.initBreadcrumbs(); } + else { + this.initBreadcrumbsComponents(); + } } - - private showSuccessNotificationMessage = ():void => { this.Notification.success({ - message: this.$filter('translate')("IMPORT_VF_MESSAGE_CREATE_FINISHED_DESCRIPTION"), - title: this.$filter('translate')("IMPORT_VF_MESSAGE_CREATE_FINISHED_TITLE") + message: this.$filter('translate')('IMPORT_VF_MESSAGE_CREATE_FINISHED_DESCRIPTION'), + title: this.$filter('translate')('IMPORT_VF_MESSAGE_CREATE_FINISHED_TITLE') }); - }; + } - private setWorkspaceButtonState = (newState:boolean, callback?:Function) => { + private setWorkspaceButtonState = (newState: boolean, callback?: Function) => { this.$scope.unsavedChanges = newState; this.$scope.unsavedChangesCallback = callback; } + private initBreadcrumbsComponents = (): void => { + let breadcrumbsComponentsObservable; + if (this.$stateParams.previousState === 'dashboard') { + breadcrumbsComponentsObservable = this.homeService.getAllComponents(true); + } else if (this.$stateParams.previousState === 'catalog') { + breadcrumbsComponentsObservable = this.catalogService.getCatalog(); + } else { + this.cacheService.remove('breadcrumbsComponentsState'); + this.cacheService.remove('breadcrumbsComponents'); + return; + } + breadcrumbsComponentsObservable.subscribe((components) => { + this.cacheService.set('breadcrumbsComponentsState', this.$stateParams.previousState); + this.cacheService.set('breadcrumbsComponents', components); + this.initBreadcrumbs(); + }); + + } + + private verifyIfDependenciesExist(): void { + let containsDependencies = []; + if (this.$scope.component.componentType && this.$scope.component.uniqueId && + this.$scope.component.lifecycleState === 'CERTIFIED' && (this.$scope.component.isService() || this.$scope.component.getComponentSubType() === 'VF')) { + this.ComponentServiceNg2.getDependencies(this.$scope.component.componentType, this.$scope.component.uniqueId).subscribe((response: IDependenciesServerResponse[]) => { + containsDependencies = response.filter((version) => version.dependencies); + if (containsDependencies.length > 0) { + this.$scope.hasNoDependencies = false; + } else { + this.$scope.hasNoDependencies = true; + } + }); + } + } } diff --git a/catalog-ui/src/app/view-models/workspace/workspace-view.html b/catalog-ui/src/app/view-models/workspace/workspace-view.html index d22262c94a..79dde943dc 100644 --- a/catalog-ui/src/app/view-models/workspace/workspace-view.html +++ b/catalog-ui/src/app/view-models/workspace/workspace-view.html @@ -22,7 +22,8 @@ {{menuComponentTitle}}
    -
    + +
    @@ -53,9 +54,11 @@
    - Switch to the latest version + Switch to the latest version + @@ -104,11 +106,11 @@
    -
    +
    {{getTabTitle()}}
    -
    +
    diff --git a/catalog-ui/src/app/view-models/workspace/workspace.less b/catalog-ui/src/app/view-models/workspace/workspace.less index 518272d45c..5c479c7370 100644 --- a/catalog-ui/src/app/view-models/workspace/workspace.less +++ b/catalog-ui/src/app/view-models/workspace/workspace.less @@ -109,7 +109,7 @@ .general-view-top-progress { width: 30%; margin: 0 auto; - min-width: 150px; + min-width: 140px; } } @@ -189,7 +189,7 @@ display: inline-block; } } - .tab-title{ + .workspace-tab-title { height: 110px; padding-left: 100px; line-height: 110px; @@ -199,6 +199,11 @@ .w-sdc-main-container-body-content { height: 100%; } + + .w-sdc-main-container-body-content-wrapper { + height: 100%; + overflow:hidden; + } } .w-sdc-main-container-body-content { // height:calc(~'100% - @{action_nav_height} - @{tab_title}'); @@ -219,7 +224,7 @@ height: calc(~'100% - @{action_nav_height}'); .w-sdc-main-container-body-content-header { display: flex; - .tab-title { + .workspace-tab-title { flex-grow: 1; } .w-sdc-main-container-body-content-action-buttons { @@ -239,4 +244,58 @@ } } } +// Fix till we remove everything to angular5 and fix all workspace style +.composition{ + .sdc-workspace-container{ + .w-sdc-main-container{ + .w-sdc-main-right-container{ + left:0; + //overflow-y: scroll; + .sdc-workspace-top-bar { + position: absolute; + left: 245px; + right: 0; + z-index: 1; + .not-latest{ + left: 270px; + } + } + .w-sdc-main-container-body-content{ + padding: 0 0 0 0; + } + + > div:first-child{ + padding: 0; + } + } + } + } +} + +.deployment { + + .sdc-workspace-container{ + .w-sdc-main-container{ + .w-sdc-main-right-container{ + left:0; + //overflow-y: scroll; + .sdc-workspace-top-bar { + position: absolute; + left: 245px; + right: 0; + z-index: 1; + .not-latest{ + left: 270px; + } + } + > div:first-child{ + padding: 0; + } + .w-sdc-main-container-body-content-wrapper { + padding: 0px; + } + } + } + } +} diff --git a/catalog-ui/src/assets/languages/en_US.json b/catalog-ui/src/assets/languages/en_US.json index 72f320d5b4..aa6a088796 100644 --- a/catalog-ui/src/assets/languages/en_US.json +++ b/catalog-ui/src/assets/languages/en_US.json @@ -28,7 +28,7 @@ "GENERAL_LABEL_SERVICE_TYPE": "Service Type:", "GENERAL_LABEL_SERVICE_ROLE": "Service Role:", "GENERAL_LABEL_STATUS": "Status:", - "GENERAL_LABEL_PROJECT_CODE": "Project Code:", + "GENERAL_LABEL_SERVICE_FUNCTION": "Service Function:", "GENERAL_LABEL_DESCRIPTION": "Description:", "GENERAL_LABEL_TAGS": "Tags:", "GENERAL_LABEL_RESOURCE_TYPE": "Resource Type:", @@ -43,10 +43,12 @@ "GENERAL_LABEL_SOURCE_SERVICE_NAME": "Source Service Name:", "GENERAL_LABEL_RESOURCE_CUSTOMIZATION_UUID": "Resource Customization UUID:", + "=========== GENERAL_TAB ===========": "", "GENERAL_TAB_LABEL_RESOURCE_MODEL_NUMBER":"Vendor Model Number", "GENERAL_TAB_LABEL_SERVICE_TYPE": "Service Type", "GENERAL_TAB_LABEL_SERVICE_ROLE": "Service Role", + "GENERAL_TAB_LABEL_SERVICE_FUNCTION": "Service Function", "=========== GENERAL ERROR PAGES ===========": "", "GENERAL_ERROR_403_TITLE": "SDC Access Denied", @@ -192,8 +194,6 @@ "WELCOME_BTN_START_TUTORIAL": "Let's start", "WELCOME_BTN_SKIP": "skip for now", "WELCOME_BTN_ACTION_DESIGN_STUDIO": "Design Studio", - "WELCOME_BTN_ACTION_CERTIFICATION_STUDIO": "Tester's Workspace", - "WELCOME_BTN_ACTION_GOVERNOR_BOARD": "Governance Board", "WELCOME_BTN_ACTION_DISTRIBUTION_STUDIO": "Distribution Studio", "WELCOME_BTN_ACTION_CATALOG": "Catalog", @@ -216,8 +216,6 @@ "NEW_SERVICE_RESOURCE_ERROR_NAME_EXISTS": "Name already exists.", "NEW_SERVICE_RESOURCE_ERROR_SPECIAL_CHARS": "Special characters not allowed.", "NEW_SERVICE_RESOURCE_ERROR_CATEGORY_REQUIRED": "category is required.", - "NEW_SERVICE_RESOURCE_ERROR_PROJECT_CODE_REQUIRED": "Project code is required.", - "NEW_SERVICE_RESOURCE_ERROR_PROJECT_CODE_NOT_VALID": "Project code is not valid.", "NEW_SERVICE_RESOURCE_ERROR_CONTACT_REQUIRED": "Contact is required.", "NEW_SERVICE_RESOURCE_ERROR_CONTACT_NOT_VALID": "Contact is not valid.", "NEW_SERVICE_RESOURCE_ERROR_SERVICE_DESCRIPTION_REQUIRED": "Service description is required.", @@ -304,6 +302,7 @@ "=========== ATTRIBUTE VIEW ===========": "", "ATTRIBUTE_VIEW_DELETE_MODAL_TITLE": "Delete Attribute Confirmation", + "ATTRIBUTE_DETAILS_MODAL_TITLE": "Attribute Details", "ATTRIBUTE_VIEW_DELETE_MODAL_TEXT": "Are you sure you want to delete '{{name}}'?", "ATTRIBUTE_EDIT_PATTERN": "Invalid value.", "NEW_ATTRIBUTE_ERROR_NAME_EXISTS":"Name already exists.", @@ -335,7 +334,6 @@ "WHATS_NEW_4_TITLE": "App Navigation", "WHATS_NEW_4_BODY": "This release introduces View and Edit modes
    1. Use the view mode when:
      • User does not have authorization to edit an Asset
      • Asset is in Check-In Mode
    2. Use the Edit Mode when:
      • User has authorization to edit an Asset
      • Asset is in Check-out Mode
    ", "WHATS_NEW_5_TITLE": "Certification Studio", - "WHATS_NEW_5_BODY": "Tester, Governor and Ops roles can view VF and Service Composition.
    They can also download the asset’s artifacts, and download the asset’s resource instance artifacts", "WHATS_NEW_6_TITLE": "Composition: Virtual Link", "WHATS_NEW_6_BODY": "The ability to link VFs via a Virtual link has been expanded. Now a Virtual link can be defined as having either Point-to-Point connectivity or Multi-point connectivity. Additionally from within a Virtual Link, Point-to-Point connectivity can be dynamically changed to Multi-Point connectivity.", "WHATS_NEW_7_TITLE": "Distribution", @@ -357,11 +355,8 @@ "NEW_USER_ERROR_USER_ID_NOT_VALID": "User id not valid.", "NEW_USER_ERROR_ROLE_REQUIRED": "User role is required.", - "=========== EMAIL_MODAL ===========": "", - "EMAIL_MODAL_TITLE": "Submit For Testing", - "EMAIL_MODAL_SUBJECT": "{{entityName}}; version {{entityVersion}}", - "EMAIL_MODAL_MESSAGE": "Enter your message here...", - "EMAIL_OUTLOOK_MESSAGE": "mailto:{{to}}?subject={{subject}} is now ready for testing&body={{message}}%0D%0A%0D%0AClick on the link below to open {{entityNameAndVersion}} that is ready for testing. %0D%0A{{link}}%0D%0A", + "=========== CONFIRMATION_MODAL ===========": "", + "CONFIRMATION_MODAL_PLACEHOLDER": "Comment...", "=========== CATEGORY_MANAGEMENT SCREEN ===========": "", "RESOURCE_CATEGORY_HEADER": "Resource Category", @@ -390,7 +385,7 @@ "DEPLOYMENT_ARTIFACT_BUTTON_ADD_OTHER": "Add Other Artifact", "DEPLOYMENT_ARTIFACT_GAB_NO_CONFIG": "Generic Artifact Browser has no columns configured" -,"=========== IMPORT VF ===========": "", + ,"=========== IMPORT VF ===========": "", "IMPORT_VF_MESSAGE_CREATE_TAKES_LONG_TIME_TITLE": "Create VF", "IMPORT_VF_MESSAGE_CREATE_TAKES_LONG_TIME_DESCRIPTION": "Your VF is being created.
    It can take up to 10 minutes.
    When done, you can view it in SDC Catalog.", "IMPORT_VF_MESSAGE_CREATE_FINISHED_TITLE": "Create/Update", @@ -412,16 +407,6 @@ "CHECKOUT_SUCCESS_MESSAGE_TITLE": "Check out", "DELETE_SUCCESS_MESSAGE_TEXT": "Deleted successfully", "DELETE_SUCCESS_MESSAGE_TITLE": "Delete", - "SUBMIT_FOR_TESTING_SUCCESS_MESSAGE_TEXT": "Submitted successfully for testing", - "SUBMIT_FOR_TESTING_SUCCESS_MESSAGE_TITLE": "Submit For Testing", - "START_TESTING_SUCCESS_MESSAGE_TEXT": "Tested successfully", - "START_TESTING_SUCCESS_MESSAGE_TITLE": "Start Testing", - "CANCEL_TESTING_SUCCESS_MESSAGE_TEXT": "Cancelled successfully", - "CANCEL_TESTING_SUCCESS_MESSAGE_TITLE": "Cancel", - "REJECT_SUCCESS_MESSAGE_TEXT": "Rejected successfully", - "REJECT_SUCCESS_MESSAGE_TITLE": "Reject", - "ACCEPT_TESTING_SUCCESS_MESSAGE_TEXT": "Accepted successfully", - "ACCEPT_TESTING_SUCCESS_MESSAGE_TITLE": "Accept", "APPROVE_SUCCESS_MESSAGE_TEXT": "Approved successfully", "APPROVE_SUCCESS_MESSAGE_TITLE": "Approve", "DISTRIBUTE_SUCCESS_MESSAGE_TEXT": "Distributed successfully", @@ -431,10 +416,11 @@ "ARCHIVE_SUCCESS_MESSAGE_TITLE":"Archive", "ARCHIVE_SUCCESS_MESSAGE_TEXT":"successfully archived", - "=========== ON BOARDING MODAL INFO MESSAGES ===========": "", - "ON_BOARDING_GENERAL_INFO": "Displays a table of VSPs created using Onboarding.
    Each row displays details for a single VSP.
    When expanded you can either import CSAR files that are yet to be imported or update CSAR files that were previously imported.", - "ON_BOARDING_IMPORT_INFO": "Displays the Onboarding repository and supports importing on-boarded CSAR files.
    Select an imported CSAR file to create a VF from the on-boarded and imported information.", - "ON_BOARDING_UPDATE_INFO": "Displays the Onboarding repository and supports updating on-boarded and previously imported CSAR files.
    Clicking Update, updates the existing VF with information available from a new version of the CSAR file.", + "=========== ON BOARDING MODAL ===========": "", + "ON_BOARDING_MODAL_SUB_TITLE": "Select one of the software product component below:", + "ON_BOARDING_GENERAL_INFO": "Displays a table of VSPs created using Onboarding.\nEach row displays details for a single VSP.\nWhen expanded you can either import CSAR files that are yet to be imported or update CSAR files that were previously imported.", + "ON_BOARDING_IMPORT_INFO": "Displays the Onboarding repository and supports importing on-boarded CSAR files.\nSelect an imported CSAR file to create a VF from the on-boarded and imported information.", + "ON_BOARDING_UPDATE_INFO": "Displays the Onboarding repository and supports updating on-boarded and previously imported CSAR files.\nClicking Update, updates the existing VF with information available from a new version of the CSAR file.", "=========== HEAT PARAMETERS MODAL INFO MESSAGES ===========": "", "DEFAULT_VALUE_INFO": "This column indicates all the default values that were declared in the Main Heat ", @@ -450,6 +436,7 @@ "=========== SERVICE PATH SELECTOR ===========": "", "SERVICE_PATH_SELECTOR_HIDE_ALL_VALUE" : "⚊ Hide all ⚊", "SERVICE_PATH_SELECTOR_SHOW_ALL_VALUE" : "⚊ Show all ⚊", + "SERVICE_OPERATION_PROPERTY_TOOLTIP_TEXT": "Service properties are defined by the input parameter type. In case you can't find a certain parameter, it might be due to a wrong type selection.", "=========== INTERFACE OPERATION ==========": "", "INTERFACE_ADD_OPERATION": "Add Operation", @@ -499,7 +486,6 @@ "PARAM_NONE_OF_TYPE": "No available properties of this type.", - "=========== PLUGIN NOT CONNECTED ===========": "", "PLUGIN_NOT_CONNECTED_ERROR_MAIN": "The \"{{pluginName}}\" plugin is currently unavailable.", "PLUGIN_NOT_CONNECTED_ERROR_SUB": "Please try again later.", @@ -531,9 +517,11 @@ "MODAL_CREATE" : "Create", "MODAL_CANCEL" : "Cancel", "MODAL_DELETE" : "Delete", + "=========== POLICY AND GROUPS ===========": "", "ADD_TARGETS" : "Add Targets", "ADD_MEMBERS" : "Add Members", + "=========== PROPERTIES ASSIGNMENT DECLARE AS POLICY ===========": "", "DELETE_POLICY_TITLE": "Delete Policy", "DELETE_POLICY_MSG": "Are you sure you want to delete policy '{{policyName}}'?", @@ -553,21 +541,31 @@ "RESOURCE_UPGRADE_STATUS_FAIL": "Automated service upgrade failed.", "SERVICE_UPGRADE_STATUS_SUCCESS": "Automated service upgrade was completed and successful.
    The services which are successfully upgraded are in checked-in state with version displayed below. Please close this popup window and proceed with design completion on the services", "SERVICE_UPGRADE_STATUS_FAIL": "Automated service upgrade failed.", - "SERVICE_CERTIFICATION_STATUS_TEXT": "Service {{serviceName}} was successfully certified", + "SERVICE_CERTIFICATION_STATUS_TEXT": "Service successfully certified", + "SERVICE_CERTIFICATION_STATUS_TITLE": "Service Certification", "SERVICE_AUTOMATED_UPGRADE_WITH_COMPONENTS_TO_UPGRADE": "The following services reference {{vspName}}.
    One or more of the services were not yet upgraded with the most recently certified version of {{vspName}}.
    Select services from the list to upgrade them with {{vspName}} {{vspVersion}}.", "SERVICE_AUTOMATED_UPGRADE_ALL_COMPONENTS_LOCKED": "The listed services reference {{vspName}}.
    These services were not upgraded with the most recently certified version of {{vspName}}. Currently they are locked from being upgraded with {{vspName}} {{vspVersion}}", - "SERVICE_AUTOMATED_UPGRADE_ALL_COMPONENTS_UPGRADED": "The listed services each reference {{vspName}} and have already been updated with the most recently certified version of the {{vspName}} {{vspVersion}}", - "=========== REQUIREMENTS AND CAPABILITIES ===========": "", - "REQ_NAME": "Requirement Name", - "REQ_RELATED_CAPABILITY": "Related Capability", - "REQ_NODE": "Node", - "REQ_RELATIONSHIP": "Relationship", - "REQ_CAP_OCCURRENCES": "Occurrences", - "REQ_CAP_OCCURRENCES_UNBOUNDED": "UNBOUNDED", - "REQ_CAP_OCCURRENCES_MIN": "Min", - "REQ_CAP_OCCURRENCES_MAX": "Max", - "CAP_NAME": "Capability Name", - "CAP_TYPE": "Capability Type", - "CAP_DESCRIPTION": "Description", - "CAP_VALID_SOURCE": "Valid Sources" + "SERVICE_AUTOMATED_UPGRADE_ALL_COMPONENTS_UPGRADED": "The listed services each reference {{vspName}} and have already been updated with the most recently certified version of the {{vspName}} {{vspVersion}}", + + "=========== ERROR_MODAL ===========": "", + "ERROR_MODAL_TEXT": "Error code: {{messageId}}
    Status code: {{status}}
    {{message}}", + "DEFAULT_ERROR_MESSAGE": "Error getting response from server", + + "=========== CONFORMANCE_LEVEL_MODAL ===========": "", + "CONFORMANCE_LEVEL_MODAL_TITLE": "Warning", + "CONFORMANCE_LEVEL_MODAL_TEXT": "

    You are about to distribute a service with models and artifacts created with an older version of the platform.For such service, new properties, metadata and requirements needed by ECOMP components will not be available.

    It is highly recommended that you upgrade the service models and artifacts.

    Click \"Continue\" if you need to distribute the current service version.
    Click \"Reject\" if you need to stop the distribution and manually upgrade the service.

    ", + + "=========== REQUIREMENTS AND CAPABILITIES ===========": "", + "REQ_NAME": "Requirement Name", + "REQ_RELATED_CAPABILITY": "Related Capability", + "REQ_NODE": "Node", + "REQ_RELATIONSHIP": "Relationship", + "REQ_CAP_OCCURRENCES": "Occurrences", + "REQ_CAP_OCCURRENCES_UNBOUNDED": "UNBOUNDED", + "REQ_CAP_OCCURRENCES_MIN": "Min", + "REQ_CAP_OCCURRENCES_MAX": "Max", + "CAP_NAME": "Capability Name", + "CAP_TYPE": "Capability Type", + "CAP_DESCRIPTION": "Description", + "CAP_VALID_SOURCE": "Valid Sources" } diff --git a/catalog-ui/src/assets/preloading.css b/catalog-ui/src/assets/preloading.css new file mode 100644 index 0000000000..1f0c2c6c3a --- /dev/null +++ b/catalog-ui/src/assets/preloading.css @@ -0,0 +1,69 @@ +html { + height: 100%; +} +body { + height: 100%; + width: 100%; + margin: 0px; + padding: 0px; + overflow:hidden; +} + +.preloading-page { + height: 100%; + width: 100%; + margin: 0px; + overflow:hidden; + background-image: linear-gradient(to bottom right, rgba(30, 36, 48, 1), rgba(59, 74, 93, 1)); + text-align: center; + display: flex; + align-items: center; + justify-content: center; + flex-direction: column; + color: #FFFFFF; +} + + .project-icon { + width: 200px; + height: 210px; + margin-top: 0%; + background-repeat: no-repeat; +} + +.preloading-page-loading { + font-size: 24px; + line-height: 44px; + font-family: Arial, Helvetica, sans-serif; + color: #1EB9F3; + margin-top: 10%; + margin-left: 3%; +} + +.preloading-page-loading span { + font-family: Arial, Helvetica, sans-serif; + font-size: 50px; + animation-name: blink; + animation-duration: 1.5s; + animation-iteration-count: infinite; + animation-fill-mode: both; +} + +.preloading-page-loading span:nth-child(2) { + animation-delay: .5s; +} + +.preloading-page-loading span:nth-child(3) { + animation-delay: 1.0s; +} + +@keyframes blink { + 0% { + opacity: .2; + } + 20% { + opacity: 1; + } + 100% { + opacity: .2; + } +} \ No newline at end of file diff --git a/catalog-ui/src/assets/styles/app.less b/catalog-ui/src/assets/styles/app.less index 0738c460e7..26ddc4677f 100644 --- a/catalog-ui/src/assets/styles/app.less +++ b/catalog-ui/src/assets/styles/app.less @@ -2,15 +2,11 @@ width: 100%; height: 100%; } - @import 'variables.less'; @import 'variables-old.less'; @import 'mixins.less'; @import 'mixins_old.less'; @import 'global.less'; -@import '../../../node_modules/sdc-ui/css/style.css'; -/* @import '../../../node_modules/sdc-ui/css/theme_1802.css'; */ - @import 'sprite-old.less'; @import 'sprite.less'; @import 'sprite-resource-icons.less'; @@ -18,7 +14,6 @@ @import 'sprite-group-icons.less'; @import 'sprite-policy-icons.less'; @import 'archive-resouce.less'; - @import 'animation.less'; @import 'buttons.less'; @import 'dark-header.less'; @@ -38,7 +33,7 @@ @import 'tooltips.less'; @import 'welcome-sprite.less'; @import 'welcome-style.less'; -@import 'notification-template.less'; +@import '../../app/view-models/shared/notification-template.less'; @import 'tables.less'; // Less insides specific files. @@ -48,9 +43,6 @@ @import '../../app/directives/elements/radiobutton/radiobutton.less'; @import '../../app/directives/ellipsis/ellipsis-directive.less'; @import '../../app/directives/file-upload/file-upload.less'; -@import '../../app/directives/graphs-v2/composition-graph/composition-graph.less'; -@import '../../app/directives/graphs-v2/deployment-graph/deployment-graph.less'; -@import '../../app/directives/graphs-v2/palette/palette.less'; @import '../../app/directives/capabilities-and-requirements/capabilities-requirements-list.less'; @import '../../app/directives/info-tooltip/info-tooltip.less'; @import '../../app/directives/inputs-and-properties/inputs/input-row.less'; @@ -77,45 +69,14 @@ @import '../../app/view-models/admin-dashboard/admin-dashboard.less'; @import '../../app/view-models/admin-dashboard/category-management/category-management.less'; @import '../../app/view-models/admin-dashboard/user-management/user-management.less'; -@import '../../app/view-models/catalog/catalog.less'; -@import '../../app/view-models/dashboard/dashboard.less'; @import '../../app/view-models/dcae-app/dcae-app.less'; -@import '../../app/view-models/forms/artifact-form/artifact-form.less'; -@import '../../app/view-models/forms/env-parameters-form/env-parameters-form.less'; @import '../../app/view-models/forms/property-forms/base-property-form/property-form-base.less'; @import '../../app/view-models/forms/property-forms/select-datatype-modal/select-datatype-modal.less'; -@import '../../app/view-models/forms/resource-instance-name-form/resource-instance-name.less'; -@import '../../app/view-models/modals/confirmation-modal/confirmation-modal.less'; -@import '../../app/view-models/modals/email-modal/email-modal.less'; @import '../../app/view-models/modals/error-modal/error.less'; -@import '../../app/view-models/modals/message-modal/message-client-modal/client-message-modal.less'; -@import '../../app/view-models/modals/message-modal/message-server-modal/server-message-modal.less'; -@import '../../app/view-models/modals/onboarding-modal/onboarding-modal.less'; @import '../../app/view-models/modals/icons-modal/icons-modal-view.less'; @import '../../app/view-models/onboard-vendor/onboard-vendor.less'; -@import '../../app/view-models/plugins/plugins-tab.less'; -@import '../../app/view-models/support/support.less'; -@import '../../app/view-models/tabs/general-tab.less'; -@import '../../app/view-models/tabs/hierarchy/hierarchy.less'; -@import '../../app/view-models/tutorial-end/tutorial-end.less'; -@import '../../app/view-models/workspace/tabs/activity-log/activity-log.less'; -@import '../../app/view-models/workspace/tabs/attributes/attributes.less'; -@import '../../app/view-models/workspace/tabs/composition/composition.less'; -@import '../../app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts.less'; -@import '../../app/view-models/workspace/tabs/composition/tabs/details/details.less'; -@import '../../app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties.less'; -@import '../../app/view-models/workspace/tabs/composition/tabs/relations/relations.less'; -@import '../../app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts.less'; -@import '../../app/view-models/workspace/tabs/deployment/deployment.less'; -@import '../../app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal.less'; -@import '../../app/view-models/workspace/tabs/distribution/distribution.less'; @import '../../app/view-models/workspace/tabs/general/general.less'; -@import '../../app/view-models/workspace/tabs/information-artifacts/information-artifacts.less'; -@import '../../app/view-models/workspace/tabs/inputs/inputs.less'; @import '../../app/view-models/workspace/tabs/properties/properties.less'; -@import '../../app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities.less'; -@import '../../app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less'; @import '../../app/view-models/workspace/tabs/interface-operation/interface-operation.less'; @import '../../app/view-models/workspace/workspace.less'; -@import '../../app/view-models/workspace/tabs/plugins/plugins-context.less'; @import 'override.less'; diff --git a/catalog-ui/src/assets/styles/global.less b/catalog-ui/src/assets/styles/global.less index 29e244e1a0..f70fc441b4 100644 --- a/catalog-ui/src/assets/styles/global.less +++ b/catalog-ui/src/assets/styles/global.less @@ -51,3 +51,12 @@ html { } } + +*[hidden] { + display: none !important; +} + +.sdc-tooltip { + max-width: 300px; + word-wrap: break-word; +} diff --git a/catalog-ui/src/app/_favicon.png b/catalog-ui/src/assets/styles/images/favicon.png similarity index 100% rename from catalog-ui/src/app/_favicon.png rename to catalog-ui/src/assets/styles/images/favicon.png diff --git a/catalog-ui/src/assets/styles/images/splashScreen/splashscreen_logo_and_text.png b/catalog-ui/src/assets/styles/images/splashScreen/splashscreen_logo_and_text.png new file mode 100644 index 0000000000000000000000000000000000000000..27d4b7b94a1b20918805334b01e6caa905aafd59 GIT binary patch literal 28515 zcmV)lK%c*fP){00BV=1^@s6u~gXs00004XF*Lt006O% z3;baP002M$Nkl)qJn}5*iY}y`+MG5Pm!XY zUF;nz*7NM%+0U*Z0s?kK5JU(NlF(6lO?G$wzwdkR&CYH%VUujKv)T8O*;nS3@BQBQ zdu^I&Xj3l{$lJW)z`%CS`lv(0=*AcsXIxu_^Q2xMW}uwPDZ z*x>qQSy^k61OhE)j0kA5#|V@cqvfnxF%oO?$!NqbHdt-al${Kbnn};T&`)GI`C%v( zImxC@0eS7REc2e$4H`W7byn6M1Zz_d5RlqY4{DM^RS@fPV=}6IB9okH3Lg*SXi`Od zFgW}?$gG%+=#tnnwM-|-t~!oljP%#6=-TP^6oR+jR#lTdiJG?C>eVfF1@}zCFnlS* z_Bo@sn5!d*2+O~)!Z+l&q2)-Rv^A#jnVqM|&1ng0Rw4yO^}X}V8_ z2+mXwAKB$OShl&#GR?c%H#8^D?AUQHpU^)^fq+X}l0x2;5i)1(s_wx+*QUQ*+$1;q`O&d44dtuwQyY>fIr-FhZ0o!;OBY#hhE6V_@1?{;H5NCmG9oeC9 z)rg4q2JV)-dS!loaaDkvWZTxu1uOmz^4<=Tw{}P^2Kx}frC&|`NiLK<$Fl5kzjp65 zuPSBgxOImwcf%niHJlpVLCzo2 z)68)zayrco%e0D~P6fX=vjbahLf&IhTn0KDE>mSw7sd?a4vI?#^Q+ji8cY?5D)+XNrsQl;W7?I)u=={KaVN za!OVm)2X01-w2dGXa|ik?n`x?7ZF@^HIPZ>PGN`$S$1L@;m-VwyoWyNZ0@U0**Z<_ zA)v`#d)V$b=iIf0-TZ;F2e4iq8QLI2GA5Bjb7ur6!t>~En0s+)?V+Xz9C+8_)~$E$ zx1ef9==$sOTN~Nex`z+h`{q)Pq3sLZG z5TF&8MWiNKFq(^{1cgE}AsN|s+7H0|4P zF{}j@O${JOOk^PzQGl>`6z4GR0DiQ5zHx=wd9%gYy8Z3FV#R?w_L?^vM(}b>?=z@$ zp*%uvhxq8h#Ar|F$!!EJ!~D0;GHzUSSl))Zm0FkPMnJTeJ4Cx{1%a%!1t;2my2aJ* z!PJ$dI3pvEimv8Rgg1=!hH2gK*POf;CYffiR)niUrrm#8(K#429|WOCai=6ZBg%rM z=X!|#iu|G@|OKM>$|e5Q52% zFd7l*pZpm4_hFEHxKWelcP?$!YKPab0_lea{l-HO_s~$i;A4Xju-xg?WH7};*h=i& zU$y9n+;?SUZPgJ1PCM06c_~v&?v}#lWxM=0VVC_1=z6*$F#!+YJME zsJ+v`NV{rjZf>EM0i$Kfg2gK@HUsvp5Wgjpo9jW9lm{$QGV+S^aIwdniJO1ME$)@K z0H?I60|YeL;|wyd%hwcKi23&I7@b?PVyiNsR&upt4X81-b=I&F9BKf(7Y-X&_Kknd>GW?etjnw0 zZry%b(FOIHj5>}~c{rmvcWVH|Av|I@ZgV@*-QK-X$4B4nVV0`2+Kw**q-)yL5P{5% zD>|EH!TYf;A47mLp=l^1M@XU730jXM*fy|Bz0bDIM;bLb@D4Ao%c~1Zx1Uy?h~>*e zsQw{TeMiaQapp2O$vgP+E-Qo(J`U|gC&-nh4ibA7hWUl+-MH75ojO@*TJ- zhHo@+fK)_>?Ob~%f-})skrxz5yI`h#@IiEklg0Eysq zNJC?mbNyTr9qaOqaNcx5cK*MTd0npRSXKM5g@xS$be};mI3jGeqcUO))$PCt#PlA$ zC9X^u+c34itxJ=f$Mt$%fmJI9QPQMp4+gobhU<88WpmQ1F1cy(to$w%~WZIL)vg`eH%bd6( ztJCrnfh(qJ4#9fy}>t{kjuVO1#iPPBBU06a;XyPo8s4-G4TH*7)Mg{OKyH zw#y?haB<1OJ9n4eil^!>0gh>EDJ1a4Z@G?CQ~2PWy|@fIC`80op2-HOw<`Z98-% zd4Yg&KSr9!101;%eZ%l2exKS!-7w6Ep%3<6ib7NkzygQj<-CxZCCkM0m^i&1d^=>6exF zv|g7pDz*C4^Sh!RxD}b+n|~rV3enkJBG0xEBHJr;%G`pd2PZWhoc+X1lRJRWsT6gE z;g$**hbP+k|OZDirB#IAPZVCe_pf5ohA!Vg1oKdCEOy;@GnkiEyojZL=tw_S&Zn26Dw z*X3&JCzPY2OKTX+P3t3{Wlb#Xkhj#U4VemZ(Rx0(ujmSF;N67YxOsT{VJ1e}%$>AQ zYjr7<;~B=M8D_?WZ;oxhBo(lVR>yizb~Lz|xxV24K;^q}t7co8oJ*Y$(?K;N5IWM$ zpa`X*jh^u(*`23G15bw~27%r`tZf@HO6dDV6#5x1`*Jx}vRt0UZx4`Do+ z-q4!#^`NZHiIF~WrLtZpuK3z5x&6i!gK_8E!xQ#aI#JFlQdu2gjMZ3{_339j-)~0ti^W5%HN8{g5fu! zH4hBGjOxBLM^$2?hxEcWK5pPkpD_3M4)uCZre2Vp*X0|Rorm?<-FRC}dqHy5pds5K zziMyTc!Y8ZF1Jryoz*GjcWVijWH(2Dxvtfo;9k6E!2BCt@#o{I8!gl@%7?eV&hMk>0?#b z+7fca!6K(dT7!TBDc%nRY#v$X~u-&cAfRT(=J@5x5LA2R(rp9AKN~hiN|F#5qGVm$@P(r88;Bjs`N@Z(RN-+>d?_+M)xaO^rgk zuIde?)Ljdj^RE+b7}$96Oe)YpZshrp&_zOng*E=aTFQ44Sd}h(N%PPf;5~xGtnOG-yD9oaLTW zqHw?Un}w(GI*iDACK;cL@HE*w{9ce5^xIgM8|R{DB|4*RB&*pagH($#*||yqwBFNA z?M65MnyH_BVtDjVIRpkwD>*%A1nu-kV zd|ob74+n(m<{=^5+iM#e8+TlTnfuict1%DR+zenmMsYIk2B0S5Q0@!NY4|+wc&y78 zb42~45vT-#5e0UGErrG7K=d1+Q%&8vL>+({*`v)I@sJI_V{qp1tfY9ypy$Zmc4NVr zSeN5#B6cPL&7`KrqFz@{wL}jrM5kXtd}|pVdcLZ-LudW=(MptCpNft^|IatHF#>z; z!u9#{p;7qeq@+DB6`^IUe+Z-jg$EU3<4h^^^wIPKvTnkyw|f!lStA(Z0r7g+cE*-X z%OAomu9u14)P*SZukboOE#!4}P;Fxyu9x4|xmLG^AzvB*FNE7 zZ@+QbBe(y#~wefG23rgHVoe~pGq`#uZP5}UG9XU zM4aD-ozFX(watHYv8lh`9oI(CnZ<+v^wT{0y>435zUyC> zx9hAw+3O{(No85=;5w)%HsVM}72&Zp7ooqH0W=5(0)O)oR0$)y-?s6-cI+k1QLV5F(0n&KIr|T>6p#GfgSn-h29F1GwGH73T1|n zP;JBbYht90UTVU~4r=!xKtg{sxD)HS&*YIF-h=U~p~sf5UH(({nq|YHS3!qr1Zod~ z(Q`I6J?ev^`vOMU0?a~>XOcrl$vC>Jrt|bbmP>!Z_RjRgUF}I%wVV@1b_4e#Q`biX z7bK^*#t?`+%!g`0ae{V_V9=PFSyJ$BUdf8ip_AIB5vV-`27gq1?(bW7FNKO;jXUeo z1<^rrw~EpLg@ZJgmZYr92x328fwXz)n%vrxuxdFcjO?~)=P@AE6Uv^EaN}{^Wm9!H zj2yOos^1PS$}U=dZ{Fq=2U3tW8i9BtaP%i7hY$L&cox>(ui?qKc4A)%rAWQR@Z=)A z&|=bEb>6WNgr_z0;w@iw^Gg`n@jy#cHKMDYk!%8r3_(bSZG^24&_DJmJ!HQ)PiM$Q2N7L` z#x6@HlJ(z11~`LS`*1hy+|j8{*hnk8rgI!H(B%};>cnsjD{d_DwJNH_JWl- zvZMBb0;KBhU;4rJ&xw=E=Ypsm*?l}7{gU5uXxEw(=2;AH-vH@_Jt|5YM z-nM(kvb+^5{sgc&sb|pEf+QS)N!a5V^l{0BJN))C+^T&k6v`5V4e1udllnzA>6REw zgx;|-k@^|-4%4!(>6Vq%v!T`S9j8*9p7Ia}r4QiQOs|-PksUY)L%_fg#wrMp336Cb z+uXvE>@KJKEOQ9D+y$xuoZV4MAsdANX5u3yLfZ$7;468B%fH6dzCUNCe^MTS!5@|M zpZ0Odx44<>8GzA(0U^C1#Z!7jTEqbYu8>YTBmIBOhK;+<9+P$dGkx%3i3WT3avZ70 zluFDF$fZYiLV<7)2P`6~8!+s)Qw+zf%IZApZ&{ss`Aq8)Or17z&%o*B$gX0lJf)4x zCjHG|@avAtm%rGhq(r=tR>jqJ${=v`$Lm@R`l#qxT*>(w_iXSx6O;}KGSe>(8gcl5 zx4eEW^qJ|$%swsakF$rjS{DwU$i>lVDZVTiEL{fj{T+IsCVxysM}O$U5QyLmIshdU(b$Tcy~ed2lhte1sqJS+#fzAY zf6_Uj(@3pm2YMPGg3JXf1IE2!=yW;P@)j+&7v*)H=u7tbg zI)s=Y`HPJjWpw>=Ox7b6zdBl6Mi;pNNzRjOchBMtgcJ6F34uc#q+vJYCQ#s`xAyPH ztjx+UK$KA(SFRj}X+OQ7vWEbia}%jKf9dDFIs^pmoS+eSGjG|7*_P?Ma(U<6`THqK zpH3nKhRoR5cHf@8_XYy?UxaQ&v_F%Pe}n>}ZbW_>5V#XSbU5dwS=QwNX-eS7vSMTZWe3!{if z#1H8i&N{jv;*tI#^mn{v=CYwws>A3S;*A8H8h3CYW(B)|x* zs`WuM#VX9}^mxbh_I8_5JF^;b`>VQ0O<=tUk&{C)HAH9dY(^8S>#Q-EPfo)A zkV>_G8`F4FS>!89kTwedN%RICfujyMq#HZ!H8MZv5*MEh-?y?0>My&$o^ME zsOE1$Ztjx8&Ye#(eC9~J?PjU!bt!LAhExRP&l1oSj!17CopAnxF2AgtcF5u)Ja4a! z7ZIRm#BpQHHO4+0kDuD-s3|lJrc$FsCyt(6of8_S+Ml&-BVIA}_t~Q}2hBMxXI}N| z*^G5o=npa7rNQL&kg3{yIqrfBhB;*9bx-^dTA82!@j;#Q4nrj;qS3d8cP647QV=@G z;A0c4BtbhkwAAn~=(2eEqurLQ7B^prDEc?S2w)^XaZPdYLR?b47Y&CiETa9wNG=;x z+@(noBn1(UH95vwb4uEQ&ANU$I_o*;g>3z5R&4urh(TG<1!K}5Q681)HIp#16U3?y zWLtv7?kcR9_6I0^C1!co&Xaw1Bdq7Gr_t5p5o6IfLP1Cl7-}Pghr;N|C*z7>U|&JE z#VhrzvGxaaEuSAWeQnNwkBZ;M<+0E3v}0E)j@wPy)TG>g2qoR(*&;Qnbkljmr0e9p z=8Va@Jf5Fk7J4jhq;Yhb2QDhpJ0@{tM^mYhR`rb3Sop8v_FQaWF6-LsrFMgi-Y!39X7Wew;#2my$)^um$_rIkHKxO3*##~ZP2OZCkcSuagbaT z?xFp;TH#g9Sn>o)0!83Z6Ea9K=TP;Czjn|68Kge}-`PGLJ>3d!9L`3REk*=tC)N}= zgk*@<9iONAwCjQu?{{0WqD$3F)+wrrz@Sf8jofCIEJj=0jQyCIV}eQEDvewqW`Fy;ta0 zW7S66U|pU+@Z+KnaHsQ!xKfhu=moV4^H|IPRoT=|;q6BobJld9FTLmN(b*H;A6%PX zW}yu_79!pP2G5CBYa(JQJ^wRR@*<*-vo^qLo4;L>&eQ2r;?pcw~>nXxU*MUvJmM?1t;6H(RE)i_b$a zn%=u;E?YEI2XtI#mIVS!ddy#WM~}rDn?&ZT{UHSKz)F(=pBCK{u>IH_w?TB#_SE@{ z5mML=-ta27h=TybUWFTDPM?Su{N zN*uOlcI>!!$>Djo+ZkzHFlxMlOE)fo5e2?b1H+>_DBEa&`rKge-L>q{A6K3S#Z)>P zmVYXH27FfhhrN6D{0a>J2^=!$)@33v0Y%*@+iKm*KnV!NIsBT&UIgEk-ZZ=WoKact za+C!AknTF|52vbw7~T^oSVYl@BRe&zB#dZeDH#FhA+xkw_F9nsytFi905*hhA9ZMi zAu+{f9yxHhWw(Rv@D-bv4*j9<+rxfbHIU+_x;g68q8=E{zra4ne}P2@g{2}f<3kwY zP@O+xDmwz%A$;J=XmH5f(K)xwJkBK2C){vX6xRM!0TPSPBwRivK*HASEC2%{MIkq^ zamb@2^oYH6#faXH@X|oMP&++#Ri@lnYa?%)yt+fjlS4$ntSLED_^tH zGp=3OGjp{^s#IrUjQHmFW?Q!Ix&@P;vA9yZV(Z%>-BH{sYQR@yk!SH zj5L9WjwKNxBQOeUe-TDRVXnw?fO0o(Y`U?TFZ0m3qrFLV=hp9X?eDFoO&Hm^Etw>u zk)4qdVF?o|#YNrabyKwD7>ak-VC5$!Ll20w?9m(G!mbv*31 z(=vSBz8al<=O-tdu5SoX1n(GbYW{&tu-)zN9VrvJ7e=GEY-9q28(98&382bkS==MP zcyX_e=UBe9!BF0LTnE(2QCLb$jn5WU7WEY8vjain^+Uf|Is340ih5JD`eKI6*wTE! z)Z)kdc3>Vht&UnB-i1WX{}0z4H3nrg;Hw>{!pT3sO7vQS~C77xiWv zorL{e&#zbhtN%9}+9Xq*BW1-*#vJ%r@dbPL?O29U`EpFg#WNr@gmaxG0)z`2;a6CQ zj!=Aj;n23(J!g-~oUUSe-43;_(qB<$s*?c08#PEM*%<=Te(nhgGBy461~^rbg4grC zJ3im4@d2GNkGmID*++`3Ix)_Rm0pE$2;P_yv@pp1ZI8XX;D~RFuAvt*h%?Fad(_n8 zKDYz!8xa0EJZIiY5Le1C+n0R~(Oq?;Fgi^0KaCqS?lyO%`1pb=hWDLHf4O4|Rg&7@ zLj!x_md8v49^X(zT?>)FayA{e)#?9@bE)d;Ugb_p9PfCPnXC_d`|f#%WO z_)6Nl+$p+c_UC>bPlqBOhuSTmYPl7i6hv*}iHZ{*v@aFR$Ggt|*Ym4YpZET%X4&?*4kNRU{BmUW zmvk;!jkq)@+K<|l$xoG`%6iBoZW=Ff5a0+z2qfwm6DL&sTjr;}9cP}|FBhM#GA}{Z zHc<&e8AvH$q(YFJ>(8O^1%oF9g8uov=B}F3?_2M@8f(z!s|S8MwfKA7_4Xv%?qIia zQ`_;u)uIOG8alt+0dTi&zStzKL67jRL>9@#HdKbQ8>tRKHQLVS!rq6 z@*`#!T{*p1a&%xUk^v}i1 zFVlOViXU>n&-_;8pb!^@xI;h?f4(UA@b)=HKlhqlI6SUG?I$z(UK*~Kj}4gnmO+s7 zvCe>yEIG*)Qg9BFT{lK}Hbio&gK2IyEZ=1(os!-6s}Y%B@2AM5J53~awVH4<9Qd;|dpRIZoui>4A z4*0Opd-%dfFfK2w{e%SEf1BpF*nsQz)hX5e_(HsDQ~UV{Jr?>aI&N=ja>B?i1_+@% z+#IaUa5=qX?KhGaN|=+jk?;U;>#2ZM0H4|jkP6XoVp7;A%eI^vAq zVVVVfW))pb)9sqp=b|6%^#0RUUFElf^!Vu?xg%!gk}R&alClZ;RKtnVQHM>YZTMlJYK!<{bOLjapZkD)JBw=JHO;$Z3DGjEH3|P48#I2s5&*CIKlYxv`nc*=bl}vY6BcYK zT7YH3{m8kgn4TjyF3%CbmAz;$Zaa!&8v#7z@_0t$rd{Tq5{Hj3xJvT6lX;CFLMe2> z1zfyzTTQ}tcUhSwID`o+7lT6prLOsLU@pBRad@xUMW+~M@IkD9yD;HMcN~QR$te*3 z0!K#ha3fguMV~KLy&NL@@q@fPLwH>8`6KW@JWG7%8MPerd!HQJRH|Sz% z@gI-Q`Os>Vd#GjkCZdtHDOwZ36zRz(427b}nUZ0gZkO7>^qpRGH@*6)qO$0=+jEB=ogcM`s z^U&S#i6c9(U?q}@qref$>p+;&j(L5|vUx{mPd1t~=mgDq8h056Xa=NkbEevarI^wS z654hHIIi6l++EOjdhz+_6c}Cw=78xXBZ}7+FT(ubPQ+_Wi8wDsV%REgr$ga$A|B59 zP0O5Y9e6;OuSV9^#}|~e$ziKLlCb3dSI`~z#(QTwK7rGCG$JV#wIwMMjMB)2_CP`u zPyNp8)BZOIbV>g&OP=rt0}n%+j^jBZ6AavC0*c>rTbo**bd z0d!K=7@=@%?LPiM*<8Fxq7<-;r|QJ;!{io_a#x}HT``5{=8)t!jMYA$F>&tjoHtUq z38GhB>2hdzm+=5#z&j&*!Uj>LjHF`Zrh})93{%3yl8xkT>$@RY@3zX$ImBmK*FwK= z^$qAj;lya{l3gjGvWe(&sXUU4;i$PWx&^_Ha#fg=pnA4^q%!#u7L((JN0<=Vuc(UnWIk zfQaf!$p|F(=u_u#ByWM=oRItDcf)dy_LK(vT%aaB+XMU?6%71B+5)ed+?)?UmF zZp%8*I^^q+Ko+Pb)Ld0e~QL;js zZ0bN&ctV7VQfNZg>GMmBRd(rW*0bA^B1??5?OD@E2C}%s2K#ULu}0Nosk}H ze8+q_zG-*m+!0wHSF<>sjA$+Om-|zRwFtV)A2x5HYY|2Bs@d+cl7+nY$ zrHm3B1f}UUyQ4%kauBpQ#NeXVkq+`T%33E5As_~(65Bmz5=$s=p^`YVOJ#Edq}Dp#f+%^V5uK-EyI7-( zS(NTgO(=Wk&iDjg&?X?%RENRgkzP*c_5PgFmm1q*8ZWw3#$5HN z)CZ`3pvI-7a0c6j&Wa6CxK%$Y@%7FvH6ED8(;CN7MFL2HmBRWHx2glr$SFInsdM%M zY7KV0unwEH1KjXUx_FgRvwRXijRz{UZAHq$qL2?u`-Zf3t{0LJr4zcAfi3%5I^>0lOaIke{0(>RX zuE4}P6GwIz6bcl=%vtj!7MJ=_x+1hxywGUQE-|{-kD4a57Bq#Yfl6^+>9Z4%Q0YR2 zCywkcMI>=Z{leBgAsMx+CI~2;DG%i)tt7Yd*Cc`ZQ{ zC_K(6kO&~Hgz=$}#L*dPkSn_p&X~*J_!O49xhVY=JMt1)nxd+q-XqW?jO6vARUWba#NSM-@&)Re-Hpe)821iM7H!5h6t^Ghw_UB@~J% zY&H5QJDRXMtZE4Gh9~39NQ+UOvk?BO<)&j-ih#VaM%~vy@1ygYN!X<~8dQ|Z5y71v zku_AE@fuu7CXbv-@@Ni7#i-5>u88hf6 z1f*sbDIVz?t05B~E(#zwy;6nT+QbC`fiXdfN4pfpp{_PAWz;m2giYgl>I3ORgjcuC zA~2y{P)#BAPqYdFoXcOo#Ji(W44$wc4yt8m6=FFo`mOv1>{ zL{}R~5g#hh1ADdgETq>cXoK6Jos4fD)(!m;I7VCF)^QxtEiJLJKI4))j zw;0)j9@^BXCEV*KTOu+K5w6!Kr>$jY#n*BbDp;n)^w>pwFW{4~kzE1gwiz4x(Yx{S(G6ahL-&BGbh08+KPxtoJf@BDsdb&_;-E+l z$3yoxc*`V=>t5FPRRR`ciOt2%NyYXCiw=znAEIqczM=e~~3dN&=- z*tLsKIW^5CVKZh1hxAUO#1N66M|izxuW7?N=^0Zw@(|e4&*y>l5GSH`R2u=pR4Fnr zrBR;#^vLcYN-PIT_!q=?gOjj6$dRr-I3&VS4TMA z;t?DSmjH+`(gQnzQe#69iy0GvDmqi1S~B*kE2wcXshvR}&_s>kYTeFzQOtE}0HxcB zhbf^$XxP*p3P^tMK$G~!iH`)p)unI_!V>TJl##l*1o!z{@U-2fzof&CZtI(BB=?M|t2c44xl%YA_r(i00H?u*yHw!L_{Y82l*%w@*oTD3EdeE%J=mEha2gMt z03c)((MbuJ`g$7AxYYPZDV%dboe0hoc}7}yt~Ev&cn13N(8ane^%rU_U2!NNepw`T z8n3383LFBA`LEd?uO?Z0b#&RY(0VHlQM99J3fhc(;p$`qJ5eAsT5Z15=Zwin)NoTaFIs#`svT-nA z%q1Xs+RlV0XbERpI>BvP{;KC(J1G)IcED2{u5D5+g#sQ@JJn6GTotjQc47^w>MxX0 zlU?CaJv(3rt`nUnNX_rzcjrS?C(c{Yb8nc0ksUCslzpJ+2^kpC8zOvgudhlvc>|*4 zmV&41Jdg|JBjscllv9QzcLft9{TUB$I0;yuOc*-LAvui~_yTDBTSf--+#4ogWH)VV zC4oUBjv95u^asEMZPO0;pO}Ph(Hk%&rxc`gge`tV1(cnf)$xqf=S=xMD`*E^VS!xu zs*Y83sHDy2wl^mnxY;X$CyY#{9sH1cMIK?`lKQCj?BE~v{_LU`27Xo2$SYtaqa3Vq zaxJN5Qly`ZeKJ-k!7`uqhMiGbTKXp5>(^3KSlqDU6Grw%-@jmIZ$7J*)V{FsZdCCIrN&PC(LuC6Y@aNk!dQ$CP1;M*`6s z`PXiE0WkC@{OGgHY!kNdGM7A8sE(+tkn)%CX0+LkEgv1rFwUB?u~T5phOdoa@Z1m{ zwDBqNlsGFr#>oHEo8#Mj9g3THSHj3nRd0UK0gu62sxDDFJ)=~_&>9GoH|$evf9cPC zX0Dn%cy`f2iHFYn5|H8nN~w^-Be14@67S3J6$#IHWZl`pvfw-nIz3fKNdP*;CP5i! zfi>tKuuSVpugI_DNGRE7_GrB`-L%d?FSttq$F^EyvPMz};1icN(h)R%kKb619&`b%t7a7c)PH8tFr3gP3Ib}zM5hGt#Z61Bpeis*x>OH3_v!5|Pk(sbV}{>c5VV6Q zGJgS@uo*bVt-_oU-!R^M>#8>Qc@e{elbt~M;pmS4F)Vu+gxNsgh4-Ko10jy)N;e{+ zQ#dr>4^Hhnz39FEvr0NsOl@2UpkH)v%26jue!^G%xnifh^P;Ei^wS<)Kelx5u4RDg za^U5fIfiabBJ3PPc)|-@gNS_Vp%dGl``wuXujIOCCxCvV!b z?q?$qd<5SbJcuzO%t*h;0IQIj{NkXqxFvRj%lT6dI4|aHl?7+;JcTDcO zACApA-e;PB#s`ruBvv?OnMNtjO*WdOcYS?A zo2g#MPt?PMQuh8~ZDV6+**|eD^C~E8;}H1L1+X3AMVo|m2#EEw?emTM?u5)QJXpOt z5ozduO7_`7Bf}}o!Hke2&`e`+hYsnJjx#;;u!bXREj!No*S3R$JNMjzVfZrWmw41$ z&U9GA$jwVff(oO$ax-e&C4695)`T}Fv|e7zqQ)(Ihc9uKOuuy4go@L)oL$n9VxU?FG-F<}TaX=o5hGmY{8o!EA|3QHE-Q`7ip zpnZE>=IS4g&;6s%^bJA_d`k_(jerKgG)goIHH@<$m0_}}aBcL|pn>)LXGQmo_~!R! z(aNZ|VZepnQo{^~MMj_}fRjjy6Dja}#$y{!TCiaKLe%~-^m_+eE}aqjqp+g&xiB=K zkU`Ynu(Z6)%x-gJG7_EZz%@ydAN0QFfG>*wj0U(H?hdK~)F7&HM33z1skv@qa|LlW z;(IeUo_JE`bCW#0krJ=w82XwR*=a;)gp>`CnCJ*TDy#la_OHd zsB)!9zsZG@q}Uuz4T&xqAq#w_HGb~!%o#~l@hS>C?6uYVflA!6kYDrc)RVCwBxn$jm6uphDD>xdSeKibZF<%>qKi7yZ#^(jWOLxu;=iC@ zzAG3Ewin|VDu%}7!5%iXH4kcVa1TzWDU9lG} zaMEj+HQz!|)kh<`xq4Ky6F*yjz;?UzIyC7->_j(|RAyE?9RTV}6<0)8HYomfa8KK8veHx=w}~T@3Gz zpB&CeKx#m7Z2K+CY;et&quUmWh{^XGMs}_@sz$b|3f##`cDzW!=ijjILfkZTJF3$% zoZJYZio!S@Jo~9_G3rzM8^#i!WsQGhT$|6xlL{uO*X)%w&{rq4FZy~!&e=ZGI2!Fc zkK;NDAO1YIQWVw)`oRH}IMX&tmmK{;@m)h^Y;00lSzbM-rmw8v5R$6KYEC>*Zm$Yo ziCkwqx?yP9y7fQVc=8d^9HNUPqWuKTiQH6gs<0qBrtF)6%hJlHsg>#jeV zX4<$}r?#K1^7OKO638C9#0JSn001uzNkl#{+j))r#BzyFWq+| z+GT9jT~${cU9iR72A6>W1_+Sgu7eJP`$q^KJh;2NLx4bVhXBC|4hb&7A-FTRyK}j} z;;#GHFWr64s#CSQYVX~N0zk%tWtGXLgwJLCVb8i5sp2o!=WJ<%DJ<5-#0%Qk`1fW8 zRgm>A5V-gI@*@$JhLaZXq8@Qb*Ltug8_|A}Gfu#l!g|h^tIjVea(i?w*$`=gt4{N} zIl7z(>;&&PH)Im|Ir6qIk5ugWD~LgQfF~_{c~g6yNq-EtCL&pYQ-CbGz{bz>WAXev zErDzIQA6FHG2o>AY?fx-*c*f2G#}?O>hF~tSd;~y$Y9Z#M=n%eyXSJu68+{Ofciq^ zoZ8T6oJXikA)2|S#s5m$J|Sb8MlZm3|KS=Eyr(LyMm9-T^98IW(U6q~dE+y#asHz9 z1^$CaSQkW43Nj8=mA}FVk2oUYhEI@F??q-%9EQ{b)Mzp;p#;HF>7tuT(tH1K|BU*i z;d)tKze*0xu%!BJ+R59J#zwKpx^{QGyZE8%FbKJ>Z9Ltqf{AKdfX3{8AJbzfv&n?R z*ghe%MeN7Ww!jCDe`?~vAbFQdM2q5IqZ3ZJ1xcPfs~g`FH2eyY>uUP3Z{c%`i(m#! zDGO4gxl3oz__@yX8@7>WD0RH;O1=R}FL79o?h4 zZ!ZqF71D9xQ=hG;=)fCtlS+_wimUd_)`X}Xct~eM54Qw`W$tK=q=~E~chHdN##n1TyhQqNPje4^8jP<5tqeVU;kulBGV#P*nZKP+8 zd>F~P``7#{=iwnbaaFGiNx)%f8`CWd$;&Z!jTcVLok1al8v`^?u&>xtBP<dXs4`T`zODIgs(+1^(~?jMWlG- z-eaOpsKMY-Zf76$oVDa_JxPW%eN>*@G>JU=JQ}~;`~gE61)L9K0zL~5SdOajq-f^q z2Z+~oVVgH-ySWp`9^WA(4s@$;eE>#zdUHFwz`Di%|V>xep|;h?`9QH;608X z5Fs)BEBobCM%f{MPO_iPxn2kr`+|~#I=^GTOzZ4WAA57#<@Kwjw1gn%$>CG|G?_`{ zN9M3d75>-^x89I9gwx^VIB^<4?sXIYLGGsUc=rfqPDpEyq8&96$v-b7vRlv_t3NiE1!yxWgTjD+${EGJ^)iP>u`R{7N zh8)J?F_ss?U1Gne-Rv{=wCw^}`>U;ebZVPtqWurr^fFGDI}R--?wy(aT6z4;kqEBx zvn_Xl>WP?=2~!zHncv*tr2+Q0er|~(_d<;#NOb#c@JNx-sqRR%CaS;8Jp!c)1?n(DjlvF2XwRzdEVA;<>Uat`>u+% zlsCm+5`(A0d?XfqGt`Z1sa-t={~!N@*wb-nd=+^&(opI#_~zKth*M5Wi-HD$I5 z%PgXDC;i>rD{30>R0{oHj=ZwhuoyxrN9wx+#s@Y)yxP*o{raPdHOi%z?D84ufjE4m za=*>w%&}q(6ct~)QO?+K{2-86dLUril*4%)>NNI8&VG6s6>DX>!6^dW)L=aKshaQU zQ+Z9&H-@64qLn5aTkvB#3)R`rj&(4t7bq2EE(wK`kX8*7Q2)XE=wU%=2lBVAY*8(G z6E4RE8rILzZEC*Gn|!*A{hKrI(*=C$L&r>K`fJWds1Yf6hTVN8k5zk&T+`p-w_D}b z6@Pb|0qJGnFMcOYp-{Lw-XH1_R&klcZ-|*Hwln1Rib?s>qU0J+%e}Mx0gN>C?Ot6D zIzsqlVqg!ME32KoU#UGlnUzV9X|jLj;(fCdN?|RI^L0CvEdG<-6zF>=-b}aZ!9FA( zM~~*>92tTRYnBZOg8t%~QxX{PdrG^3XoW7oVvpLXRQD4TFJ;UM@(=VMv^eXgTYZ<< zA9JCco+Mud3V1(Ym*T_w%#&k>VHAK@#dg@|=MixI_(8Bo5R*C9KXcRtS@UDg%27PxQ3{!g#E+ozAK*?S-#(jlVWejteO)rDXhG($oNR z^J5uZ5A*MKOo#iz`CDRJdqKA{iegcFhlOiZpL|$ITazU!Lu9uwoUtx`DC*N8X#lwx zBSv_2f&%A!uWsEP2)#>1k?XdO>$csAl3^d%uPLCp_QzAZWcK!C%T1>=p*b-+mX`>l zUe1c0&CN0<)bkf_!oU;Y|?%lXl^^X%4z|urByd)iqKil}Dm)VbJwJ)`2X zp0{IsuWjusRCI_9BZnBwvuCYYENp9MyK~vG%GKyjah+6vZaOHVPj@d8bI zz?s>D2@uPaQrN{xx=LpW7g;9S)@ok; zm^v^0bn=kmk%uq>fRLUS0MzsrR)wypztb484;)*7av5S@k9%-9JQ~H91$?DJRK8(w z=vE)EgfLp6(DW(`8I-XqeWK|b!qvF6Vq5NYjM$q}E?uZm26u${oW=P}FE#kl{_{CA z$6LG*M9Mg#amf4F+qP#d;+I`};*2vOu!YvVLx&V&Ej+&QgDNo_VRuMcBn&Vz$+kWz zd}k64DKMCbeYsk?yn$0e@w&R1#Oj0=|gu0 z?E=!O6}993{;A`AiMuK$^V9n5V_4G`w(^W16IXzPY0y&go>Dx>X;N49(v**ty!2; z8$HiAgVcUas#Q&%c`T_CipMoe_8K5OVgskWulBg&x(<6_le^c2h!t zJ4n*Zusp}(z<#|kE3J*(5C7TOxpBvOWRSf757_K;d-D2*KP7)j8xIuaMz$e2m4@6+ zb8~Zx?=81nc6yHd2fB#C{QICbc`$>>06}C3z=@ve5Z(t*eF%FsWZtfz^|$VAQRpCt ze>z@i^WfVaEaUymryBfWBlcyl7%6j69(si}?)r9mbl?^n8l{HRtvVoPd0pv2xMoTU2_ft!?d~d`n zbQuUrZ^oO|O6(gq*@H^Ow%>^$f1z_pm7zg!EoqBMIRgPfpCr?v;3u zo1OH&TvHr+Y0tdtH&fvfyMIgj!qlsrW|vH3+BzO|=~XuHK)yA%WL3**(SiEgfQ#9f z=BeJP!6V|mK*~?@0b*CQn3{iV{aUr;hdsv!qA3#*Zk92Ak2lxQtSx{zj)~apJ&elB zZ>~(eP(54NZIRq->^K4H{uR~9-f!{D-(eM!N!FRnfLfWF*Qa1Z;mO5+iY!ZIuvNwd{>y{=M~i<~|B5 zQl6o!+I-|2euKlBzlZh#N^C25JTvhYQ~-}VTbppYo;Mo!l**mVW-p7IWqVy#+phLa zB#!|ORbU=E{AiSm-3CqjnfMwt_$q{vu}}K#BFtKS!Mt^mwoMO>AhBddM>_tJfX2?d zorLGR|9ty<$I^;&J@zDj86jNy>4GQxnq+_LxhjJ>nVgDfkonbbt5=7VNe+cp2=cB@ zVQ8t0+KjcT!pyR^{33JkEtU>}NPgg&fWzujb&ZXT>o88?nO1C~Skhb@0Dkm4QnOh7 z1HE5d2kr0b#8ZdFQ_sOBI)(62uETp!$OfmR* z+l~0Z>3ut5lVcg^c&4;+(oAmpbg}W!nb~Ci0Wf?)m13&&-+!bly#O*~*<~D!?0CjM zuXH{4g2QSjD~2uXIQKiouEit9YjXdQJ5Tk)V`?h+sCth=E%5xnm$JI!L0P*!cwh^& z_VT-=G?1XG)FW>2BXUu31&$^c&v)%q-vhnnhKK+14`$F6eDzaYr}Kf0+=LP>Mp9lJ zlT67zAso>-ZZtB5hhG^Lq3i4&_q3MZ^bqb;(X9t)j{;84o?DW_Pc+j*uT0b>e;ZNp z+uq^NZ@laNti2X8b|_Lrb1a)xVN`KYI`hWk45@RAM>1)dWK+nZMD>c>E9ZX81FzJD zn+s=YKRC^iD-KiJux_$xz2}9g?5WAXXl)dUqJ5~waMD!Vey7Vv8 zWr=lY^%)KlgKhMP2$GMVi)ctG43l2xi~{VUT_)`_ybyg*jdW5}A_hP~DeoS0#C#Sd zf<}Hy*V4%fI2JWXM%*$ZME>$3zudzE${`vZsDVe5lMok;+AxYl7r4xeBP53H@JzJc zH+|P?Q{L!Uww4A6wiCZfb0AMH(;AY30$V=9}!F*7qe9Je=KWnbFWF zz1)!DBV!avp_G>_#dH_%4E8@{PZ9s#bBUnKZkAuBSmUbcx6gk5xs&R9w%HT+YjkYR(C*;5l(YHa$2d$0?q z*C=*NrSjTGCxwZk`O2eV-U&*g!FhK(%ta@F>6n&=(i*>ZtDg;EAW<802}R_yC-&D`3K2|mh|$3{yldfM!ibdd#Vk) zntQj*3!hnNsmw?+XUKzZLg8|zZ8!Y}avH$@!o4T9q}$+$`P@w{i(tYmfhaN6T)I#U zdT&T8Cj>{|c&&9mUhGdTR^1jFw3IyYS2s&1Vf^p`!;Rge8VMc&lM9!f$q|;6NbXQE z-q8V8M_d>Y77MO@W789D6G^~@weoN-!t1`P9}tp;9$w}a6wU)kG4L(024upm1CHO0 zqv0dD2&1v`D@{s38xbuvZL;MM9$)}EjNR3xUGd+eACrOj%8h@@)o$S!+`c)AP!+uo z@D@pe!4#(d#ela=iVg`Wc2FVg_!dDamNLV^c!$To?3Vs>)iLAhlz~ z2eMZ)$Kh2|zd2vppwE@HOo=Sy-Cg|&eZj9q@;~SBcHc}jI8%iLzgnHVDA~OXiT=zT+T0_0C-x42}uOId1kwrn0XdFkxwQ_l=2e6<=Q|mhPK@PdfE#$ z>P?i^OfvFwh_@8&!E+h{kjvpj4Uyyv%?NT*OB@dZHQkdF++U$uRJpwhB z@r&nC1?sRnN3+kAvzffs7p`WW29N4;~6J1a_^Brb% z?$C0{&0j<=BKfmHH;<=X(=lQ;zV)~lcN7jm^X*M<0!>UYwU-8Cic#$!DzZq@Z@Pn)~mkUQ_c2zQ7^! zzceo)l_LOrb9KuL(Hm6z9_RdK`tJo{;I)mxThc5lf@9GO_U_d`8$X_s1~^e;(KP(< zdn~kK>gwv!)W@SS#t9^J{X@1Cfjs%Kmy?LLNQeQ*n7=ANHL@bxj4LryjiPV^1gLI= z1glFD&%&v;orF%Za|vlES9A~;_Wvyn6qI6wNuhy;zueDQMNWD0J zIz(7MuK{l9fg~!&rbF0HJB94GdG+4d?#cqhrXRS43asmNrc~yyh61~BetX}NC#Le( zqy35B*R?HrM0JAndS6Q0p7@~#q{^R=#_|869e^b6o?}!`;Yu+3h)mf*Th})J<4^ib zYLwrfSzrSBT$R+H^^{Z#`Xu+s!(wKG;d-gt4}t&f**IcJI+hr{_0VuR(h# zjk=|at^w7D9wH$%z3EgGnaMkW30(@U)_R``vzb$Kp!sc}U&wC9{GPDOaKlV@qJ)c!c4ePZ6n_TRp zOuc5uur5A&lBj2QNf5v@JXO8)n%3{Ex-EQdjdMjR*_Wfb^Vkpm)1?@Bb76@~_+;Dn z2v>L?vnww5Q8MA);Ki!i&9f^2a8;@Rx_8{wAv;;LH;OpAN+oDlcjIPtL&GZe@UBOc zxZ(;fJ^NnZLv&rm(H>LDwkmtWvz;C<(2xUWsK_+(!fy zo{@dL@YzD#k)(Y92A;p8J);P`$2QFHWH{n+Y!5r5@;F&;!9bcMlRa2A4zI=Mww3rZ zb3W5Z7nV;3j4wdu5CY;peh!^{gzHIGHJ$$n!H3J?e^LI0Vyb3y9nH116X~J$;mvwv z!iS45O>{$3!3x?|>a1ekK%wbS1^;H=(aS{YEjBiGPv@W}+40C) zB^t9OQl2;h+)62Rru$739dh1mqOG7` zwI~DZC+2Qfuo&Vl^Gki?BLk%+ z-qQ?rKzI$OriR9p)#1ONr*x}ZgO`3E_$<_4A|FGeBSrnJwiOe{qXr{7DWI8Axu)UH z)jkHK6_u=O<%@U1dv@epdyj{^8yH{_{wQygXm|1M2+8=8ntaqum5us$CfW!7TcIVsCp_H%whct0=c@B%8Pc>sWx;{1sQejCy~I zwC}77&5uz$1u=mr4}ESE*a-MeHj&fjXiv2Hgy~NE>5-ngLnOCzQxSxoKc37cvrIAX z>Pws%FTxDwu3aCsac3xT6Y`64rNj~?wbwKQJg1Enn&k8>h&cKtTwSU6k`Nr=1(KC; zM*4gh%Z@e`-podME+xG#)u{Hh9{GfpYRb%WjVPQ~m~Ka^M>ec1?@uDg6$DvIgiF&di3#44+kT3F zigb}HYj(tk3i<{ApzgMkcN7@Hy`($vOo>Jp!9o6Xd;HdD@LTs68=E9kIF-uKKI;m< zBKxyO@}fU)OQ2%pAO@tK?jks|1cJ6iTjYg|!hxw(=5Qu#@{^j-a6jfP)}>!RJf^!6pu_A?*?hb*6rsb!(ksOu#@j!Gb>eE3IsC2Q`N`H`d@nZa%81w?v! zem;ogJnNtUjtM_J>hd<zNn09n)EQ0+P)os9_IC=JGKwp$a%}HkH znQ7j-Y2t|=33_v9q%$dVKvA5_F|8(KaJ$qc@|C!JoXc|CuGm;vKn_RgVkH)z9kIgOCP%q>5XDG4F#hfvLD=8F$FHtP1e> z@pwW5{HmVyIKurAXg5!mK2@pwJtBz2X&nnFkmpC*(@AQg(<4r5z6ug*llDxP)c@q1 z73NME)(+8n7bIZ9N0xo#SM#IL3FqQxjh&ZSY5L%ifo}&7h+?|<=eUy^$157~fdKIX zig%L5S-oWVJMgNoRv=|J7wlEMTQQ%P7w(AD?T>5?3O**tR@ro>xn39HBvf^z?+HQ^ zr!aR#j@0^IhPH2&Yl3Q)mo&t6)u$48SB_Qow#f$Cb}7l>A>LL@e37fzFZ_w;6hI)< z>nl~bFzlc&m2f%&G##kt5?zRMz>khnq2`q|=M?$KwiyN>wre5S;6;+-gL!b^F$v2` zJQ02zaokSs;tpv(ZH`iLI>#(o7_26iD;;d8O+hU#X7SW)xD|=sOTnK)n@Cy#e78jP zXU)A@nB2$OOvQ$_IzQ;9-XOok1jS_T>7!j_t6Ud6q70KzN+V27f4!C4ep}mD$*!(& zK3w!{d>)vl$r7vi7K(Gni?C?5Gz=T8=rG@a*FuiVO>mQRmPreV!&;IU)>+?axC&YQ z4y{@dOgl#D4yv)n(9|T^C8l(LKQ+yMBY1STTcBgesH!6KWW>1`urA{+RD|;kutdX) zfK@RcRmN8)dG#Jd0E_leYpkc^4@4yv-xbEoB`=xpWt#7+1^>d(i%W7=u(sY0bL4<7 z@7L^yB%bEK9O_$lXIW8w8leulFvJs~6T=7qnFC3Wf!#VX;b4EdZoCAXgq?xGuMv(J zVsQHEl8LzRnhm~8Xn#WS2UllNRJn%)`sqUCJb+Ud+S|?DNzX>4wo@OK*P{bn;a5Z^ zTumVJu)Br;SJp<%_L(68DRQ<2oWGtJX>r@}v$Sjm`}-lj-8X?+-k}^)Std!3wip#P zc0Get-1Jo6lcxMt(Xmzn6_#;m@gst#;usj7e9e@mn_!m|Rd(UZ9e@A_GY0s8#bghH z>4$%`rT~7#z)9g-LFPxJq$+y)(hXpcu1RMK#B5Zeopq>uyF6N1OhC95m;&d;Sw@!@ z?{=cBSt4cZk`s12XbA6ab3blHo9-X`81RbeBuBp|X?%uq=HKXbxkD!V7|Sgj%$>Cs z*Br-^01I*6KP*Z5bA2jlXxWn< z`ZFkeJDQSMCN>tfL`q4QMEol<@hfdHi6kVp_cvSI0)9v|vEKYlnehy>)KS8Bb8Du0 zUWO)&_xh52UtlecKdeTCr z_@TK||H)Kd($%6aC;5LOr z_RBKgbHHIPU4uULV2`9xtV;&XOib8b4o1+V7gxJc=zZ-^fTnFX3ozK7oWiC?F6}1D zd{|ZO@7;=GK)uknF_m~zDejvugGWd!&|as^6REN9iKRSqq%ECm;M-eUa#T4Sb8)9y zN4y%JY6(Dx{C`MYINNI4+S*NVGizXh-!8IDTy++NUv&YuS^|voLkb&)gHP;^Eeu-g7ov#1m}&ZWjW@B9o2rwDqD4;FM~cHfxlI5BVi`` z_ApB7mL+$~?;X8tifFo;WSA|0=VXuKUFOT#Ld)_;(6Z8b&o*!6s% zB|MTWS-SnIB(%IMniv&RZd#wbehO8gzVXD$uG`^OamBNv5z~Mp~$_K6m$CIpT>WmjJNKj|$PI=hicBMWi$Pf-s``VIdZL+J2)tMPTH+@dGH;(8{)e(&7jZ()pMf$aUU1Chd3Pg|p zc~58auDqf`uf?s}lIvb`_IlzGWzS(RlWUuAd3aoFjd1@{l!5Os)>q5APwY+yl2(Q8 zz(#@6A8#`%!vs@&2lKX?HGbD?%cis-o020CmBDX79#D@atRDt9uM-&tcJ`o(q*fZx z6SW;y?3ue>lAF%S+%sSCosA*PNv#qL2|^jhjx?{1_OB zS4L65wVXAR7dP5N-fO0ZvV2jENLvnzNgL7zs-U>xZW{5v`(C{Pi@L851n~KL?Y%oX z)fM5SmdKH#;|~{P6iY07o#DT#|CENE|2XRXYa zqJF2rcYTRJZW{FFjA6m2ucb0BGFR%i$$vyM837zDy)c-uEVO#6RW%;Y;8%6}h0Q=E3 z(}hLeA=|nt?YKjN^8AyK)hYcU^HSml<0=2Jc(q-zVa%vF7UpoB^~8UJck(gq?mIzL zv!YigCArkw_3NRZG0x4Jan zkh;LA(DvH6pL8$>htvC@JVBVJ7Mm(D^<90znYy4j!}}|&z0GY;d9(m8iCpZRX+APl zma_xZ<`a9vZ;CW_FMaX(o1SxqoKwU+*pfEU zU3>VBX{T@$i%N9noZStgy!6V?Dp~~%^%+W;=3uIa@9W .s; .font-type > ._1;} diff --git a/catalog-ui/src/assets/styles/mixins_old.less b/catalog-ui/src/assets/styles/mixins_old.less index 0e32684282..3f9a970d84 100644 --- a/catalog-ui/src/assets/styles/mixins_old.less +++ b/catalog-ui/src/assets/styles/mixins_old.less @@ -1,3 +1,4 @@ +@import "variables-old"; @import "variables"; .font-color { @@ -246,8 +247,8 @@ .s_1 {.font-color > .s; .font-type > ._1;} .s_10 { - .font-color > .s; - .font-type > ._10; + .font-color > .s; + .font-type > ._10; } .s_12 {.font-color > .s; .font-type > ._12;} diff --git a/catalog-ui/src/assets/styles/override.less b/catalog-ui/src/assets/styles/override.less index 960be234f9..ae8fc4219e 100644 --- a/catalog-ui/src/assets/styles/override.less +++ b/catalog-ui/src/assets/styles/override.less @@ -22,51 +22,18 @@ @sdcui_color_purple: #9063cd; @sdcui_color_light-purple: #caa2dd; -/* override sdc-ui library tabs */ -body.composition { - - .sdc-tabs { - .sdc-tab { - background-color: @sdcui_color_white; - border: 1px solid @sdcui_color_silver; - border-left: none; - display: inline-block; - height: 36px; - text-align: center; - cursor: pointer; - padding: 2px 10px 0 10px; - margin: 0; - - - &:first-child { - border-left: 1px solid @sdcui_color_silver; - } - &.sdc-tab-active { - background-color: @sdcui_color_silver; - } - &[disabled] { - opacity: 0.3; - cursor: default; - } - } - &.sdc-tabs-header { - .sdc-tab { - font-size: 24px; - } - } - &.sdc-tabs-menu { - .sdc-tab { - font-size: 14px; - padding: 0px 10px 4px 10px; - } - } - .sdc-tab-content { - margin-top: 0; - } - } - +.sdc-modal .sdc-modal__wrapper .sdc-modal__header { + height:auto; } //override sdc-ui version 53 css, used by onboarding. This can be removed after we update past version 42 sdc-modal { position: static !important; } + +.sdc-modal .sdc-modal__wrapper .sdc-modal__header { + height: auto; +} + +.sdc-menu-list { + z-index: 9999999; +} \ No newline at end of file diff --git a/catalog-ui/src/assets/styles/sprite-resource-icons.less b/catalog-ui/src/assets/styles/sprite-resource-icons.less index 0ada1c8711..1c5c852ef0 100644 --- a/catalog-ui/src/assets/styles/sprite-resource-icons.less +++ b/catalog-ui/src/assets/styles/sprite-resource-icons.less @@ -155,10 +155,10 @@ .sprite-resource-icons.cp.medium { background-position: -151px -4048px; width: 21px; height: 21px;} .sprite-resource-icons.cp.large { background-position: -194px -4034px; width: 60px; height: 60px;} -.sprite-resource-icons.vl { background-position: -210px -2591px; width: 28px; height: 28px;} -.sprite-resource-icons.vl.small { background-position: -210px -2591px; width: 28px; height: 28px;} -.sprite-resource-icons.vl.medium { background-position: -141px -2579px; width: 40px; height: 40px;} -.sprite-resource-icons.vl.large { background-position: -70px -2560px; width: 60px; height: 60px;} +.sprite-resource-icons.vl { background-position: -90px -4328px; width: 28px; height: 28px;} +.sprite-resource-icons.vl.small { background-position: -90px -4328px; width: 28px; height: 28px;} +.sprite-resource-icons.vl.medium { background-position: -151px -4338px; width: 40px; height: 40px;} +.sprite-resource-icons.vl.large { background-position: -214px -4344px; width: 60px; height: 60px;} .sprite-resource-icons.cloudep { background-position: -282px -2225px; width: 63px; height: 43px;} .sprite-resource-icons.cloudep.small { background-position: -209px -2241px; width: 28px; height: 28px;} diff --git a/catalog-ui/src/assets/styles/table-flex.less b/catalog-ui/src/assets/styles/table-flex.less index 19355ddd80..3ac014cc1b 100644 --- a/catalog-ui/src/assets/styles/table-flex.less +++ b/catalog-ui/src/assets/styles/table-flex.less @@ -118,32 +118,37 @@ line-height: 0px; text-align: center; - - button { + .table-delete-btn { background-color: transparent; border: none; .sprite; - opacity: 0.8; - } - .table-delete-btn { .sprite.e-sdc-small-icon-delete; + opacity: 0.8; } .table-edit-btn { + background-color: transparent; + border: none; + .sprite; .e-sdc-small-icon-pencil; + opacity: 0.8; margin-right: 10px; } .table-save-btn { + background-color: transparent; + border: none; + .sprite; .sprite.e-sdc-green-save; } .table-download-btn { + background-color: transparent; + border: none; + .hand; margin-left: 10px; + opacity: 0.8; + .sprite; .sprite.e-sdc-small-download; } - .table-magnifier-btn { - margin-left: 10px; - .sprite.magnification-glass; - } } } diff --git a/catalog-ui/src/assets/styles/table-style.less b/catalog-ui/src/assets/styles/table-style.less new file mode 100644 index 0000000000..fa61a669b0 --- /dev/null +++ b/catalog-ui/src/assets/styles/table-style.less @@ -0,0 +1,89 @@ +@import "./override"; + +:host ::ng-deep { + + .externalActionLabel { + color: @sdcui_color_blue; + } + + .ngx-datatable { + border: 1px solid @sdcui_color_light-gray; + > div { + height: 100%; + min-height: 500px; + datatable-body { + height: calc(100% - 50px) !important; + overflow-y: auto; + overflow-x: hidden; + max-height: 500px; + } + } + //********************************************* + + .datatable-header { + background-color: @sdcui_color_silver; + border-bottom: 1px solid @sdcui_color_light-gray; + + .datatable-header-inner { + height: 100%; + align-items: center; + + .datatable-header-cell { + box-sizing: border-box; + color: @sdcui_color_dark-gray; + border-right: 1px solid @sdcui_color_light-gray; + font-weight: bold; + text-align: center; + padding: 10px; + + .datatable-icon-up { + border-left: 5px solid transparent; + border-right: 5px solid transparent; + border-bottom: 5px solid @sdcui_color_dark-gray; + } + + .datatable-icon-down { + border-left: 5px solid transparent; + border-right: 5px solid transparent; + border-top: 5px solid @sdcui_color_dark-gray; + } + } + } + } + + .datatable-body-cell { + padding: 5px 20px; + border-bottom: 1px solid @sdcui_color_light-gray; + border-right: 1px solid @sdcui_color_light-gray; + font-family: OpenSans-Regular, sans-serif; + font-size: 13px; + font-weight: normal; + .label { + font-family: OpenSans-Regular, sans-serif; + font-size: 13px; + color: @sdcui_color_gray; + } + } + .datatable-body-row:hover { + background-color: @sdcui_color_light-silver; + } + + } + .datatable-row-detail { + padding: 10px 25px; + border-bottom: 1px solid @sdcui_color_light-gray; + } + + .empty-row { + padding: 10px; + } + +} + +.expand-collapse-cell { + display: flex; + align-items: center; + .expand-collapse-icon { + padding-right: 10px; + } +} \ No newline at end of file diff --git a/catalog-ui/src/index.html b/catalog-ui/src/index.html index eb67796a16..4e1b73bcab 100644 --- a/catalog-ui/src/index.html +++ b/catalog-ui/src/index.html @@ -20,18 +20,27 @@ SDC + - + -Loading... + + + +
    +
    +
    Loading...
    +
    +
    + diff --git a/catalog-ui/src/jest/jest-global-mocks.ts b/catalog-ui/src/jest/jest-global-mocks.ts new file mode 100644 index 0000000000..9e56d6dd77 --- /dev/null +++ b/catalog-ui/src/jest/jest-global-mocks.ts @@ -0,0 +1,16 @@ +const mock = () => { + let storage = {}; + return { + getItem: key => (key in storage ? storage[key] : null), + setItem: (key, value) => (storage[key] = value || ''), + removeItem: key => delete storage[key], + clear: () => (storage = {}) + }; + }; + + Object.defineProperty(window, 'localStorage', { value: mock() }); + Object.defineProperty(window, 'sessionStorage', { value: mock() }); + Object.defineProperty(window, 'getComputedStyle', { + value: () => ['-webkit-appearance'], + + }); \ No newline at end of file diff --git a/catalog-ui/src/jest/mocks/artifacts-mock.ts b/catalog-ui/src/jest/mocks/artifacts-mock.ts new file mode 100644 index 0000000000..3cb8741987 --- /dev/null +++ b/catalog-ui/src/jest/mocks/artifacts-mock.ts @@ -0,0 +1,799 @@ +export const informationalArtifactsMock = { artifacts: { + "cloudquestionnaire": { + "listHeatParameters": [], + "timeout": 0, + "creationDate": 1547991325209, + "description": "asfasfasf", + "uniqueId": "0a76315b-529e-49bd-8459-a6a0696c4b93.cloudquestionnaire", + "artifactName": "AutoRecovery-save-of-The-new-Tal's-bible-of-ATT-image-(005).asd", + "artifactType": "OTHER", + "generated": false, + "artifactLabel": "cloudquestionnaire", + "artifactUUID": "32c1acf4-a2ec-4f56-b319-5274fb746e5e", + "artifactVersion": "1", + "heatParameters": [], + "artifactGroupType": "INFORMATIONAL", + "heatParamsUpdateDate": null, + "artifactChecksum": "ODVhYjYyMGM4NmU5Y2IyMjVjZWIxMTU4OTRjZmY4Mjc=", + "generatedFromId": null, + "mandatory": true, + "serviceApi": false, + "payloadUpdateDate": 1548774782731, + "lastUpdateDate": 1548774782192, + "creatorFullName": "Carlos Santana", + "duplicated": false, + "esId": "0a76315b-529e-49bd-8459-a6a0696c4b93.cloudquestionnaire", + "artifactDisplayName": "Cloud Questionnaire (completed)", + "userIdCreator": "cs0008", + "updaterFullName": "Carlos Santana", + "userIdLastUpdater": "cs0008", + "isFromCsar": false, + "apiUrl": null, + "artifactRepository": null, + "artifactCreator": null, + "version": null, + "ownerId": null, + "empty": false, + "type": null + }, + "features": { + "payloadData": null, + "listHeatParameters": null, + "timeout": 0, + "creationDate": 1547991325209, + "description": null, + "uniqueId": "debae48f-52da-44da-a0ae-b44441ea9abc.features", + "artifactName": null, + "artifactType": "OTHER", + "artifactRef": null, + "requiredArtifacts": null, + "generated": false, + "artifactLabel": "features", + "artifactUUID": null, + "artifactVersion": "0", + "heatParameters": null, + "artifactGroupType": "INFORMATIONAL", + "heatParamsUpdateDate": null, + "artifactChecksum": null, + "generatedFromId": null, + "mandatory": true, + "serviceApi": false, + "payloadUpdateDate": null, + "lastUpdateDate": 1547991325209, + "creatorFullName": "Carlos Santana", + "duplicated": true, + "esId": null, + "artifactDisplayName": "Features", + "userIdCreator": "cs0008", + "updaterFullName": "Carlos Santana", + "userIdLastUpdater": "cs0008", + "isFromCsar": false, + "apiUrl": null, + "artifactRepository": null, + "artifactCreator": null, + "version": null, + "ownerId": null, + "empty": false, + "type": null + }, + "vendortestresult": { + "payloadData": null, + "listHeatParameters": null, + "timeout": 0, + "creationDate": 1547991325209, + "description": null, + "uniqueId": "debae48f-52da-44da-a0ae-b44441ea9abc.vendortestresult", + "artifactName": null, + "artifactType": "OTHER", + "artifactRef": null, + "requiredArtifacts": null, + "generated": false, + "artifactLabel": "vendortestresult", + "artifactUUID": null, + "artifactVersion": "0", + "heatParameters": null, + "artifactGroupType": "INFORMATIONAL", + "heatParamsUpdateDate": null, + "artifactChecksum": null, + "generatedFromId": null, + "mandatory": true, + "serviceApi": false, + "payloadUpdateDate": null, + "lastUpdateDate": 1547991325209, + "creatorFullName": "Carlos Santana", + "duplicated": true, + "esId": null, + "artifactDisplayName": "Vendor Test Result", + "userIdCreator": "cs0008", + "updaterFullName": "Carlos Santana", + "userIdLastUpdater": "cs0008", + "isFromCsar": false, + "apiUrl": null, + "artifactRepository": null, + "artifactCreator": null, + "version": null, + "ownerId": null, + "empty": false, + "type": null + }, + "vspvmmevspdror1informationtxt": { + "payloadData": null, + "listHeatParameters": null, + "timeout": 0, + "creationDate": 1547991328134, + "description": "Artifact created from csar", + "uniqueId": "debae48f-52da-44da-a0ae-b44441ea9abc.vspvmmevspdror1informationtxt", + "artifactName": "VSP_Vmme_VSP_Dror1_Information.txt", + "artifactType": "GUIDE", + "artifactRef": null, + "requiredArtifacts": [], + "generated": false, + "artifactLabel": "vspvmmevspdror1informationtxt", + "artifactUUID": "2fd130af-853c-4d4a-bc6b-8e9ab037911a", + "artifactVersion": "1", + "heatParameters": null, + "artifactGroupType": "INFORMATIONAL", + "heatParamsUpdateDate": null, + "artifactChecksum": "NjFmZmIxZjVlZDA3NDc2M2U2NzRiYmU3MjhlYTYyZDI=", + "generatedFromId": null, + "mandatory": false, + "serviceApi": false, + "payloadUpdateDate": 1547991328137, + "lastUpdateDate": 1547991328134, + "creatorFullName": null, + "duplicated": true, + "esId": "debae48f-52da-44da-a0ae-b44441ea9abc.vspvmmevspdror1informationtxt", + "artifactDisplayName": "VSP_Vmme_VSP_Dror1_Information", + "userIdCreator": null, + "updaterFullName": "Carlos Santana", + "userIdLastUpdater": "cs0008", + "isFromCsar": true, + "apiUrl": null, + "artifactRepository": null, + "artifactCreator": "cs0008", + "version": null, + "ownerId": null, + "empty": false, + "type": null + }, + "testscripts": { + "payloadData": null, + "listHeatParameters": null, + "timeout": 0, + "creationDate": 1547991325209, + "description": null, + "uniqueId": "debae48f-52da-44da-a0ae-b44441ea9abc.testscripts", + "artifactName": null, + "artifactType": "OTHER", + "artifactRef": null, + "requiredArtifacts": null, + "generated": false, + "artifactLabel": "testscripts", + "artifactUUID": null, + "artifactVersion": "0", + "heatParameters": null, + "artifactGroupType": "INFORMATIONAL", + "heatParamsUpdateDate": null, + "artifactChecksum": null, + "generatedFromId": null, + "mandatory": true, + "serviceApi": false, + "payloadUpdateDate": null, + "lastUpdateDate": 1547991325209, + "creatorFullName": "Carlos Santana", + "duplicated": true, + "esId": null, + "artifactDisplayName": "Test Scripts", + "userIdCreator": "cs0008", + "updaterFullName": "Carlos Santana", + "userIdLastUpdater": "cs0008", + "isFromCsar": false, + "apiUrl": null, + "artifactRepository": null, + "artifactCreator": null, + "version": null, + "ownerId": null, + "empty": false, + "type": null + }, + "testtt": { + "payloadData": null, + "listHeatParameters": null, + "timeout": 0, + "creationDate": 1548592242499, + "description": "ttttt", + "uniqueId": "0a76315b-529e-49bd-8459-a6a0696c4b93.testtt", + "artifactName": "ParticipantStartSh_DF0BA5751BF84E0AABDD4B6DA83B3B0C.exe", + "artifactType": "OTHER", + "artifactRef": null, + "requiredArtifacts": null, + "generated": false, + "artifactLabel": "testtt", + "artifactUUID": "66e47ed0-41dd-4a52-acd6-b9b81c0de938", + "artifactVersion": "1", + "heatParameters": null, + "artifactGroupType": "INFORMATIONAL", + "heatParamsUpdateDate": null, + "artifactChecksum": "ZmRmZTAyNTFkNDk3ZWU5M2M1MzYyYWU4MmFmMWJlNzE=", + "generatedFromId": null, + "mandatory": false, + "serviceApi": false, + "payloadUpdateDate": 1548592243018, + "lastUpdateDate": 1548592242499, + "creatorFullName": null, + "duplicated": false, + "esId": "0a76315b-529e-49bd-8459-a6a0696c4b93.testtt", + "artifactDisplayName": "testtt", + "userIdCreator": null, + "updaterFullName": "Carlos Santana", + "userIdLastUpdater": "cs0008", + "isFromCsar": false, + "apiUrl": null, + "artifactRepository": null, + "artifactCreator": "cs0008", + "version": null, + "ownerId": null, + "empty": false, + "type": null + }, + "resourcesecuritytemplate": { + "payloadData": null, + "listHeatParameters": null, + "timeout": 0, + "creationDate": 1547991325209, + "description": null, + "uniqueId": "debae48f-52da-44da-a0ae-b44441ea9abc.resourcesecuritytemplate", + "artifactName": null, + "artifactType": "OTHER", + "artifactRef": null, + "requiredArtifacts": null, + "generated": false, + "artifactLabel": "resourcesecuritytemplate", + "artifactUUID": null, + "artifactVersion": "0", + "heatParameters": null, + "artifactGroupType": "INFORMATIONAL", + "heatParamsUpdateDate": null, + "artifactChecksum": null, + "generatedFromId": null, + "mandatory": true, + "serviceApi": false, + "payloadUpdateDate": null, + "lastUpdateDate": 1547991325209, + "creatorFullName": "Carlos Santana", + "duplicated": true, + "esId": null, + "artifactDisplayName": "Resource Security Template", + "userIdCreator": "cs0008", + "updaterFullName": "Carlos Santana", + "userIdLastUpdater": "cs0008", + "isFromCsar": false, + "apiUrl": null, + "artifactRepository": null, + "artifactCreator": null, + "version": null, + "ownerId": null, + "empty": false, + "type": null + }, + "heattemplatefromvendor": { + "payloadData": null, + "listHeatParameters": null, + "timeout": 0, + "creationDate": 1547991325209, + "description": null, + "uniqueId": "debae48f-52da-44da-a0ae-b44441ea9abc.heattemplatefromvendor", + "artifactName": null, + "artifactType": "HEAT", + "artifactRef": null, + "requiredArtifacts": null, + "generated": false, + "artifactLabel": "heattemplatefromvendor", + "artifactUUID": null, + "artifactVersion": "0", + "heatParameters": null, + "artifactGroupType": "INFORMATIONAL", + "heatParamsUpdateDate": null, + "artifactChecksum": null, + "generatedFromId": null, + "mandatory": true, + "serviceApi": false, + "payloadUpdateDate": null, + "lastUpdateDate": 1547991325209, + "creatorFullName": "Carlos Santana", + "duplicated": true, + "esId": null, + "artifactDisplayName": "HEAT Template from Vendor", + "userIdCreator": "cs0008", + "updaterFullName": "Carlos Santana", + "userIdLastUpdater": "cs0008", + "isFromCsar": false, + "apiUrl": null, + "artifactRepository": null, + "artifactCreator": null, + "version": null, + "ownerId": null, + "empty": false, + "type": null + }, + "capacity": { + "payloadData": null, + "listHeatParameters": null, + "timeout": 0, + "creationDate": 1547991325209, + "description": null, + "uniqueId": "0a76315b-529e-49bd-8459-a6a0696c4b93.capacity", + "artifactName": null, + "artifactType": "OTHER", + "artifactRef": null, + "requiredArtifacts": null, + "generated": false, + "artifactLabel": "capacity", + "artifactUUID": null, + "artifactVersion": "2", + "heatParameters": null, + "artifactGroupType": "INFORMATIONAL", + "heatParamsUpdateDate": null, + "artifactChecksum": null, + "generatedFromId": null, + "mandatory": true, + "serviceApi": false, + "payloadUpdateDate": 1548774818030, + "lastUpdateDate": 1548774812999, + "creatorFullName": "Carlos Santana", + "duplicated": false, + "esId": null, + "artifactDisplayName": "Capacity", + "userIdCreator": "cs0008", + "updaterFullName": "Carlos Santana", + "userIdLastUpdater": "cs0008", + "isFromCsar": false, + "apiUrl": null, + "artifactRepository": null, + "artifactCreator": null, + "version": null, + "ownerId": null, + "empty": false, + "type": null + } + } +} + +export const toscaArtifactMock = { + toscaArtifacts: { + toscaArtifacts: { + assettoscacsar: { + artifactDisplayName: "Tosca Template", + artifactLabel: "assettoscatemplate", + artifactType: "TOSCA_TEMPLATE", + artifactName: "service-Asfasfasf-template.yml", + description: "TOSCA representation of the asset", + uniqueId: "a4bbd47a-5644-49f8-828b-525c6deac154.assettoscatemplate" + }, + assettoscatemplate: { + artifactDisplayName: "Tosca Template", + artifactLabel: "assettoscatemplate", + artifactName: "service-Asfasfasf-template.yml", + artifactType: "TOSCA_TEMPLATE", + uniqueId: "a4bbd47a-5644-49f8-828b-525c6deac154.assettoscatemplate" + }, + } + } +} + +export const deploymentArtifactMock = { + deploymentArtifacts: { + "heatvol2": { + "payloadData": null, + "listHeatParameters": [ + { + "uniqueId": null, + "name": "oam_0_volume_name_0", + "type": "string", + "description": "name for compact flash 1 for active OAM", + "currentValue": "oam_0_cf1", + "defaultValue": null, + "version": null, + "ownerId": null, + "empty": false + }, + { + "uniqueId": null, + "name": "oam_0_volume_size_0", + "type": "number", + "description": "size in gb for compact flash 1 active OAM", + "currentValue": "25", + "defaultValue": null, + "version": null, + "ownerId": null, + "empty": false + }, + { + "uniqueId": null, + "name": "oam_1_volume_name_0", + "type": "string", + "description": "name for compact flash 1 for standby OAM", + "currentValue": "oam_1_cf1", + "defaultValue": null, + "version": null, + "ownerId": null, + "empty": false + }, + { + "uniqueId": null, + "name": "oam_1_volume_size_0", + "type": "number", + "description": "size in gb for compact flash 1 for standby OAM", + "currentValue": "25", + "defaultValue": null, + "version": null, + "ownerId": null, + "empty": false + }, + { + "uniqueId": null, + "name": "oam_0_volume_name_1", + "type": "string", + "description": "name for compact flash 2 for active OAM", + "currentValue": "oam_0_cf2", + "defaultValue": null, + "version": null, + "ownerId": null, + "empty": false + }, + { + "uniqueId": null, + "name": "oam_0_volume_size_1", + "type": "number", + "description": "size in gb for compact flash 2 for active OAM", + "currentValue": "25", + "defaultValue": null, + "version": null, + "ownerId": null, + "empty": false + }, + { + "uniqueId": null, + "name": "oam_1_volume_name_1", + "type": "string", + "description": "name for compact flash 2 for standby OAM", + "currentValue": "oam_1_cf2", + "defaultValue": null, + "version": null, + "ownerId": null, + "empty": false + }, + { + "uniqueId": null, + "name": "oam_1_volume_size_1", + "type": "number", + "description": "size in gb for compact flash 2 for standby OAM", + "currentValue": "25", + "defaultValue": null, + "version": null, + "ownerId": null, + "empty": false + } + ], + "timeout": 60, + "creationDate": 1547991328467, + "description": "created from csar", + "uniqueId": "debae48f-52da-44da-a0ae-b44441ea9abc.heatvol2", + "artifactName": "base_vepdg_volume.yaml", + "artifactType": "HEAT_VOL", + "artifactRef": null, + "requiredArtifacts": [], + "generated": false, + "artifactLabel": "heatvol2", + "artifactUUID": "148be9e1-ed72-4587-ae66-0ee3354a8e3d", + "artifactVersion": "2", + "heatParameters": [], + "artifactGroupType": "DEPLOYMENT", + "heatParamsUpdateDate": null, + "artifactChecksum": "YWNlNDljNmZiZTcyODhhYTM5MzU3ZmIzZTg3NWQzNTY=", + "generatedFromId": null, + "mandatory": false, + "serviceApi": false, + "payloadUpdateDate": 1547991328532, + "lastUpdateDate": 1547991328467, + "creatorFullName": null, + "duplicated": true, + "esId": "debae48f-52da-44da-a0ae-b44441ea9abc.heatvol2", + "artifactDisplayName": "base_vepdg_volume", + "userIdCreator": null, + "updaterFullName": "Carlos Santana", + "userIdLastUpdater": "cs0008", + "isFromCsar": true, + "apiUrl": null, + "artifactRepository": null, + "artifactCreator": "cs0008", + "version": null, + "ownerId": null, + "empty": false, + "type": null + }, + "heatvol2env": { + "payloadData": null, + "listHeatParameters": null, + "timeout": 0, + "creationDate": 1547991328534, + "description": "VF Auto-generated HEAT Environment deployment artifact", + "uniqueId": "debae48f-52da-44da-a0ae-b44441ea9abc.heatvol2env", + "artifactName": "base_vepdg_volume.env", + "artifactType": "HEAT_ENV", + "artifactRef": null, + "requiredArtifacts": null, + "generated": false, + "artifactLabel": "heatvol2env", + "artifactUUID": null, + "artifactVersion": "0", + "heatParameters": null, + "artifactGroupType": "DEPLOYMENT", + "heatParamsUpdateDate": 1547991328534, + "artifactChecksum": null, + "generatedFromId": "debae48f-52da-44da-a0ae-b44441ea9abc.heatvol2", + "mandatory": true, + "serviceApi": false, + "payloadUpdateDate": null, + "lastUpdateDate": 1547991328534, + "creatorFullName": "Carlos Santana", + "duplicated": true, + "esId": null, + "artifactDisplayName": "VF HEAT ENV", + "userIdCreator": "cs0008", + "updaterFullName": "Carlos Santana", + "userIdLastUpdater": "cs0008", + "isFromCsar": true, + "apiUrl": null, + "artifactRepository": null, + "artifactCreator": null, + "version": null, + "ownerId": null, + "empty": false, + "type": null + }, + "vflicense": { + "payloadData": null, + "listHeatParameters": null, + "timeout": 0, + "creationDate": 1547991328061, + "description": "VF license file", + "uniqueId": "debae48f-52da-44da-a0ae-b44441ea9abc.vflicense", + "artifactName": "vf-license-model.xml", + "artifactType": "VF_LICENSE", + "artifactRef": null, + "requiredArtifacts": [], + "generated": false, + "artifactLabel": "vflicense", + "artifactUUID": "f9347089-6605-4714-97ba-a678490e69a2", + "artifactVersion": "1", + "heatParameters": null, + "artifactGroupType": "DEPLOYMENT", + "heatParamsUpdateDate": null, + "artifactChecksum": "ZDE3MzEyYWUyZGRlNDkwYWZiZTY0MmMyNTgxOGNjNzM=", + "generatedFromId": null, + "mandatory": false, + "serviceApi": false, + "payloadUpdateDate": 1547991328069, + "lastUpdateDate": 1547991328061, + "creatorFullName": null, + "duplicated": true, + "esId": "debae48f-52da-44da-a0ae-b44441ea9abc.vflicense", + "artifactDisplayName": "VF License", + "userIdCreator": null, + "updaterFullName": "Carlos Santana", + "userIdLastUpdater": "cs0008", + "isFromCsar": true, + "apiUrl": null, + "artifactRepository": null, + "artifactCreator": "cs0008", + "version": null, + "ownerId": null, + "empty": false, + "type": null + }, + "heatnested5": { + "payloadData": null, + "listHeatParameters": null, + "timeout": 0, + "creationDate": 1547991328718, + "description": "created from csar", + "uniqueId": "debae48f-52da-44da-a0ae-b44441ea9abc.heatnested5", + "artifactName": "nested_lb_vepdg.yaml", + "artifactType": "HEAT_NESTED", + "artifactRef": null, + "requiredArtifacts": [], + "generated": false, + "artifactLabel": "heatnested5", + "artifactUUID": "c1ba8d08-242f-4916-8733-6f4d3f8fc5ac", + "artifactVersion": "1", + "heatParameters": null, + "artifactGroupType": "DEPLOYMENT", + "heatParamsUpdateDate": null, + "artifactChecksum": "ZjA4NTU5MzgyMWFhZjVlYWE0NmJkOGRmYmQ0OTNjMDI=", + "generatedFromId": null, + "mandatory": false, + "serviceApi": false, + "payloadUpdateDate": 1547991328731, + "lastUpdateDate": 1547991328718, + "creatorFullName": null, + "duplicated": true, + "esId": "debae48f-52da-44da-a0ae-b44441ea9abc.heatnested5", + "artifactDisplayName": "nested_lb_vepdg", + "userIdCreator": null, + "updaterFullName": "Carlos Santana", + "userIdLastUpdater": "cs0008", + "isFromCsar": true, + "apiUrl": null, + "artifactRepository": null, + "artifactCreator": "cs0008", + "version": null, + "ownerId": null, + "empty": false, + "type": null + }, + "heatnested4": { + "payloadData": null, + "listHeatParameters": null, + "timeout": 0, + "creationDate": 1547991328649, + "description": "created from csar", + "uniqueId": "debae48f-52da-44da-a0ae-b44441ea9abc.heatnested4", + "artifactName": "nested_mg_vepdg.yaml", + "artifactType": "HEAT_NESTED", + "artifactRef": null, + "requiredArtifacts": [], + "generated": false, + "artifactLabel": "heatnested4", + "artifactUUID": "5eac381a-a07d-427f-9ff1-eb87e6492302", + "artifactVersion": "1", + "heatParameters": null, + "artifactGroupType": "DEPLOYMENT", + "heatParamsUpdateDate": null, + "artifactChecksum": "ODNkODJlODhmZTYwNDMwZTViZWYxMGM3ZGVkMTg3Y2I=", + "generatedFromId": null, + "mandatory": false, + "serviceApi": false, + "payloadUpdateDate": 1547991328660, + "lastUpdateDate": 1547991328649, + "creatorFullName": null, + "duplicated": true, + "esId": "debae48f-52da-44da-a0ae-b44441ea9abc.heatnested4", + "artifactDisplayName": "nested_mg_vepdg", + "userIdCreator": null, + "updaterFullName": "Carlos Santana", + "userIdLastUpdater": "cs0008", + "isFromCsar": true, + "apiUrl": null, + "artifactRepository": null, + "artifactCreator": "cs0008", + "version": null, + "ownerId": null, + "empty": false, + "type": null + }, + "heat1": { + "payloadData": null, + "listHeatParameters": [], + "timeout": 60, + "creationDate": 1547991328284, + "description": "created from csar", + "uniqueId": "debae48f-52da-44da-a0ae-b44441ea9abc.heat1", + "artifactName": "base_vepdg.yaml", + "artifactType": "HEAT", + "artifactRef": null, + "requiredArtifacts": [ + "nested_oam_vepdg.yaml", + "nested_mg_vepdg.yaml", + "nested_lb_vepdg.yaml" + ], + "generated": false, + "artifactLabel": "heat1", + "artifactUUID": "3b29d5a5-f22c-4d1a-a882-c3631947686e", + "artifactVersion": "2", + "artifactGroupType": "DEPLOYMENT", + "heatParamsUpdateDate": null, + "artifactChecksum": "MjA5Mzc1MDIyMmVmZmMwYWI4ODc1YzA3NDZmZDU4NjA=", + "generatedFromId": null, + "mandatory": false, + "serviceApi": false, + "payloadUpdateDate": 1547991328410, + "lastUpdateDate": 1547991328284, + "creatorFullName": null, + "duplicated": true, + "esId": "debae48f-52da-44da-a0ae-b44441ea9abc.heat1", + "artifactDisplayName": "base_vepdg", + "userIdCreator": null, + "updaterFullName": "Carlos Santana", + "userIdLastUpdater": "cs0008", + "isFromCsar": true, + "apiUrl": null, + "artifactRepository": null, + "artifactCreator": "cs0008", + "version": null, + "ownerId": null, + "empty": false, + "type": null + }, + "vendorlicense": { + "payloadData": null, + "listHeatParameters": null, + "timeout": 0, + "creationDate": 1547991328011, + "description": " Vendor license file", + "uniqueId": "debae48f-52da-44da-a0ae-b44441ea9abc.vendorlicense", + "artifactName": "vendor-license-model.xml", + "artifactType": "VENDOR_LICENSE", + "artifactRef": null, + "requiredArtifacts": [], + "generated": false, + "artifactLabel": "vendorlicense", + "artifactUUID": "548aa629-2e90-4c69-983f-6ce41e8c3877", + "artifactVersion": "1", + "heatParameters": null, + "artifactGroupType": "DEPLOYMENT", + "heatParamsUpdateDate": null, + "artifactChecksum": "ZDQ0NDg4M2ExYjM3M2YxZDM3YmNlMjI2MjYzMTA0Njc=", + "generatedFromId": null, + "mandatory": false, + "serviceApi": false, + "payloadUpdateDate": 1547991328020, + "lastUpdateDate": 1547991328011, + "creatorFullName": null, + "duplicated": true, + "esId": "debae48f-52da-44da-a0ae-b44441ea9abc.vendorlicense", + "artifactDisplayName": "Vendor License", + "userIdCreator": null, + "updaterFullName": "Carlos Santana", + "userIdLastUpdater": "cs0008", + "isFromCsar": true, + "apiUrl": null, + "artifactRepository": null, + "artifactCreator": "cs0008", + "version": null, + "ownerId": null, + "empty": false, + "type": null + }, + "heat1env": { + "payloadData": null, + "listHeatParameters": null, + "timeout": 0, + "creationDate": 1547991328413, + "description": "VF Auto-generated HEAT Environment deployment artifact", + "uniqueId": "debae48f-52da-44da-a0ae-b44441ea9abc.heat1env", + "artifactName": "base_vepdg.env", + "artifactType": "HEAT_ENV", + "artifactRef": null, + "requiredArtifacts": null, + "generated": false, + "artifactLabel": "heat1env", + "artifactUUID": null, + "artifactVersion": "0", + "heatParameters": null, + "artifactGroupType": "DEPLOYMENT", + "heatParamsUpdateDate": 1547991328413, + "artifactChecksum": null, + "generatedFromId": "debae48f-52da-44da-a0ae-b44441ea9abc.heat1", + "mandatory": true, + "serviceApi": false, + "payloadUpdateDate": null, + "lastUpdateDate": 1547991328413, + "creatorFullName": "Carlos Santana", + "duplicated": true, + "esId": null, + "artifactDisplayName": "VF HEAT ENV", + "userIdCreator": "cs0008", + "updaterFullName": "Carlos Santana", + "userIdLastUpdater": "cs0008", + "isFromCsar": true, + "apiUrl": null, + "artifactRepository": null, + "artifactCreator": null, + "version": null, + "ownerId": null, + "empty": false, + "type": null + } + } +} \ No newline at end of file diff --git a/catalog-ui/src/jest/mocks/categories.mock.ts b/catalog-ui/src/jest/mocks/categories.mock.ts new file mode 100644 index 0000000000..49a5e1e279 --- /dev/null +++ b/catalog-ui/src/jest/mocks/categories.mock.ts @@ -0,0 +1,36 @@ +export const categoriesElements = + [ + {"name":"Allotted Resource","normalizedName":"allotted resource","uniqueId":"resourceNewCategory.allotted resource","icons":null,"subcategories":[{"name":"Tunnel XConnect","normalizedName":"tunnel xconnect","uniqueId":"resourceNewCategory.allotted resource.tunnel xconnect","icons":["tunnel_x_connect"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Contrail Route","normalizedName":"contrail route","uniqueId":"resourceNewCategory.allotted resource.contrail route","icons":["contrail_route"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Security Zone","normalizedName":"security zone","uniqueId":"resourceNewCategory.allotted resource.security zone","icons":["security_zone"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Allotted Resource","normalizedName":"allotted resource","uniqueId":"resourceNewCategory.allotted resource.allotted resource","icons":["allotted_resource"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"IP Mux Demux","normalizedName":"ip mux demux","uniqueId":"resourceNewCategory.allotted resource.ip mux demux","icons":["ip_mux_demux"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Service Admin","normalizedName":"service admin","uniqueId":"resourceNewCategory.allotted resource.service admin","icons":["service_admin"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null}],"version":null,"ownerId":null,"empty":false,"type":null}, + + {"name":"Application L4+","normalizedName":"application l4+","uniqueId":"resourceNewCategory.application l4+","icons":null,"subcategories":[{"name":"Media Servers","normalizedName":"media servers","uniqueId":"resourceNewCategory.application l4+.media servers","icons":["applicationServer"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Load Balancer","normalizedName":"load balancer","uniqueId":"resourceNewCategory.application l4+.load balancer","icons":["loadBalancer"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Application Server","normalizedName":"application server","uniqueId":"resourceNewCategory.application l4+.application server","icons":["applicationServer"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Web Server","normalizedName":"web server","uniqueId":"resourceNewCategory.application l4+.web server","icons":["applicationServer"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Call Control","normalizedName":"call control","uniqueId":"resourceNewCategory.application l4+.call control","icons":["call_controll"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Border Element","normalizedName":"border element","uniqueId":"resourceNewCategory.application l4+.border element","icons":["borderElement"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Database","normalizedName":"database","uniqueId":"resourceNewCategory.application l4+.database","icons":["database"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Firewall","normalizedName":"firewall","uniqueId":"resourceNewCategory.application l4+.firewall","icons":["firewall"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null}],"version":null,"ownerId":null,"empty":false,"type":null}, + + {"name":"Configuration","normalizedName":"configuration","uniqueId":"resourceNewCategory.configuration","icons":null,"subcategories":[{"name":"Configuration","normalizedName":"configuration","uniqueId":"resourceNewCategory.configuration.configuration","icons":["pmc"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null}],"version":null,"ownerId":null,"empty":false,"type":null}, + + {"name":"DCAE Component","normalizedName":"dcae component","uniqueId":"resourceNewCategory.dcae component","icons":null,"subcategories":[{"name":"Microservice","normalizedName":"microservice","uniqueId":"resourceNewCategory.dcae component.microservice","icons":["dcae_microservice"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Policy","normalizedName":"policy","uniqueId":"resourceNewCategory.dcae component.policy","icons":["dcae_policy"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Collector","normalizedName":"collector","uniqueId":"resourceNewCategory.dcae component.collector","icons":["dcae_collector"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Analytics","normalizedName":"analytics","uniqueId":"resourceNewCategory.dcae component.analytics","icons":["dcae_analytics"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Utility","normalizedName":"utility","uniqueId":"resourceNewCategory.dcae component.utility","icons":["dcae_utilty"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Database","normalizedName":"database","uniqueId":"resourceNewCategory.dcae component.database","icons":["dcae_database"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Source","normalizedName":"source","uniqueId":"resourceNewCategory.dcae component.source","icons":["dcae_source"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Machine Learning","normalizedName":"machine learning","uniqueId":"resourceNewCategory.dcae component.machine learning","icons":["dcae_machineLearning"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null}],"version":null,"ownerId":null,"empty":false,"type":null}, + + {"name":"E2E Service","normalizedName":"e2e service","uniqueId":"serviceNewCategory.e2e service","icons":["network_l_1-3"],"subcategories":null,"version":null,"ownerId":null,"empty":false,"type":null}, + + {"name":"Generic","normalizedName":"generic","uniqueId":"resourceNewCategory.generic","icons":null,"subcategories":[{"name":"Infrastructure","normalizedName":"infrastructure","uniqueId":"resourceNewCategory.generic.infrastructure","icons":["connector"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Network Elements","normalizedName":"network elements","uniqueId":"resourceNewCategory.generic.network elements","icons":["network","connector"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Database","normalizedName":"database","uniqueId":"resourceNewCategory.generic.database","icons":["database"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Rules","normalizedName":"rules","uniqueId":"resourceNewCategory.generic.rules","icons":["networkrules","securityrules"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Abstract","normalizedName":"abstract","uniqueId":"resourceNewCategory.generic.abstract","icons":["objectStorage","compute"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null}, {"name":"Network Service","normalizedName":"network service","uniqueId":"resourceNewCategory.generic.network service","icons":["network"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null}],"version":null,"ownerId":null,"empty":false,"type":null}, + + {"name":"Mobility","normalizedName":"mobility","uniqueId":"serviceNewCategory.mobility","icons":["mobility"],"subcategories":null,"version":null,"ownerId":null,"empty":false,"type":null}, + + {"name":"Network Connectivity","normalizedName":"network connectivity","uniqueId":"resourceNewCategory.network connectivity","icons":null,"subcategories":[{"name":"Virtual Links","normalizedName":"virtual links","uniqueId":"resourceNewCategory.network connectivity.virtual links","icons":["vl"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Connection Points","normalizedName":"connection points","uniqueId":"resourceNewCategory.network connectivity.connection points","icons":["cp"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null}],"version":null,"ownerId":null,"empty":false,"type":null}, + + {"name":"Network L1-3","normalizedName":"network l1-3","uniqueId":"serviceNewCategory.network l1-3","icons":["network_l_1-3"],"subcategories":null,"version":null,"ownerId":null,"empty":false,"type":null}, + + {"name":"Network L2-3","normalizedName":"network l2-3","uniqueId":"resourceNewCategory.network l2-3","icons":null,"subcategories":[{"name":"WAN Connectors","normalizedName":"wan connectors","uniqueId":"resourceNewCategory.network l2-3.wan connectors","icons":["network","connector","port"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"LAN Connectors","normalizedName":"lan connectors","uniqueId":"resourceNewCategory.network l2-3.lan connectors","icons":["network","connector","port"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Router","normalizedName":"router","uniqueId":"resourceNewCategory.network l2-3.router","icons":["router","vRouter"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Gateway","normalizedName":"gateway","uniqueId":"resourceNewCategory.network l2-3.gateway","icons":["gateway"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Infrastructure","normalizedName":"infrastructure","uniqueId":"resourceNewCategory.network l2-3.infrastructure","icons":["ucpe"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null}],"version":null,"ownerId":null,"empty":false,"type":null}, + + {"name":"Network L4+","normalizedName":"network l4+","uniqueId":"serviceNewCategory.network l4+","icons":["network_l_4"],"subcategories":null,"version":null,"ownerId":null,"empty":false,"type":null}, + + {"name":"Network L4+","normalizedName":"network l4+","uniqueId":"resourceNewCategory.network l4+","icons":null,"subcategories":[{"name":"Common Network Resources","normalizedName":"common network resources","uniqueId":"resourceNewCategory.network l4+.common network resources","icons":["network"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null}],"version":null,"ownerId":null,"empty":false,"type":null}, + + {"name":"Network Service","normalizedName":"network service","uniqueId":"serviceNewCategory.network service","icons":["network_l_1-3"],"subcategories":null,"version":null,"ownerId":null,"empty":false,"type":null}, + + {"name":"Template","normalizedName":"template","uniqueId":"resourceNewCategory.template","icons":null,"subcategories":[{"name":"Monitoring Template","normalizedName":"monitoring template","uniqueId":"resourceNewCategory.template.monitoring template","icons":["monitoring_template"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null},{"name":"Base Monitoring Template","normalizedName":"base monitoring template","uniqueId":"resourceNewCategory.template.base monitoring template","icons":["monitoring_template"],"groupings":null,"version":null,"ownerId":null,"empty":false,"type":null}],"version":null,"ownerId":null,"empty":false,"type":null}, + + {"name":"VoIP Call Control","normalizedName":"voip call control","uniqueId":"serviceNewCategory.voip call control","icons":["call_controll"],"subcategories":null,"version":null,"ownerId":null,"empty":false,"type":null}, + ] + + + + diff --git a/catalog-ui/src/jest/mocks/component-instance.mock.ts b/catalog-ui/src/jest/mocks/component-instance.mock.ts new file mode 100644 index 0000000000..0fb02064a5 --- /dev/null +++ b/catalog-ui/src/jest/mocks/component-instance.mock.ts @@ -0,0 +1,148 @@ +export const componentInstancesMock = [ + { + "uniqueId": "74f76b7d-1813-4436-97af-dc5bf6b63586.2a6cf1ea-6561-41f2-ae73-e1bdd0d1427d.datafabric_int_net_id_rvn", + "normalizedName": "datafabric_int_net_id_rvn", + "name": "dataFabric_int_net_id_RVN", + "creationTime": 1549890959623, + "icon": "vl", + "originType": "VL", + "propertyValueCounter": 1, + "originArchived": false, + "description": null, + "modificationTime": 1549890959976, + "customizationUUID": "ac0abf57-5d9d-472c-bd10-a65e348dd418", + "invariantName": "datafabric_int_net_id_rvn", + "componentName": "ContrailV2VirtualNetwork", + "sourceModelName": null, + "componentUid": "2a6cf1ea-6561-41f2-ae73-e1bdd0d1427d", + "componentVersion": "2.0", + "sourceModelUid": null, + "sourceModelInvariant": null, + "sourceModelUuid": null, + "posX": 690.0, + "posY": 340.0 + }, + { + "uniqueId": "74f76b7d-1813-4436-97af-dc5bf6b63586.2a6cf1ea-6561-41f2-ae73-e1bdd0d1427d.controlfabric_int_net_id_rvn", + "normalizedName": "controlfabric_int_net_id_rvn", + "name": "controlFabric_int_net_id_RVN", + "creationTime": 1549890959609, + "icon": "vl", + "originType": "VL", + "propertyValueCounter": 1, + "originArchived": false, + "description": null, + "modificationTime": 1549890959976, + "customizationUUID": "6a95ce69-4eed-4c1b-a097-c96ffdc9cc8d", + "invariantName": "controlfabric_int_net_id_rvn", + "componentName": "ContrailV2VirtualNetwork", + "sourceModelName": null, + "componentUid": "2a6cf1ea-6561-41f2-ae73-e1bdd0d1427d", + "componentVersion": "2.0", + "sourceModelUid": null, + "sourceModelInvariant": null, + "sourceModelUuid": null, + "posX": 690.0, + "posY": 540.0 + }, + { + "uniqueId": "74f76b7d-1813-4436-97af-dc5bf6b63586.7c11da42-a7dc-47f2-8ac4-992f2d3cdc56.oam_1", + "normalizedName": "oam_1", + "name": "oam_1", + "creationTime": 1549890959622, + "icon": "defaulticon", + "originType": "CVFC", + "propertyValueCounter": 1, + "originArchived": false, + "description": null, + "modificationTime": 1549890959976, + "customizationUUID": "734e6f22-6a70-4738-9d31-6b6f24352259", + "invariantName": "oam_1", + "componentName": "orit_vmme-nodes.heat.oamCvfc", + "sourceModelName": null, + "componentUid": "7c11da42-a7dc-47f2-8ac4-992f2d3cdc56", + "componentVersion": "2.0", + "posX": 675.0, + "posY": 125.0 + }, + { + "uniqueId": "74f76b7d-1813-4436-97af-dc5bf6b63586.8a1d8169-d91f-4cb8-9af1-5c353dca2acf.mg_3", + "normalizedName": "mg_3", + "name": "mg_3", + "creationTime": 1549890959622, + "icon": "defaulticon", + "originType": "CVFC", + "propertyValueCounter": 1, + "originArchived": false, + "description": null, + "modificationTime": 1549890959976, + "customizationUUID": "880260f9-b422-4618-bb30-2f2f275e18f1", + "invariantName": "mg_3", + "componentName": "orit_vmme-nodes.heat.mgCvfc", + "sourceModelName": null, + "componentUid": "8a1d8169-d91f-4cb8-9af1-5c353dca2acf", + "componentVersion": "2.0", + "posX": 475.0, + "posY": 125.0 + }, { + + "uniqueId": "74f76b7d-1813-4436-97af-dc5bf6b63586.7937f019-b009-42bd-a523-bc751e590fed.lb_1", + "normalizedName": "lb_1", + "name": "lb_1", + "creationTime": 1549890959608, + "icon": "defaulticon", + "originType": "CVFC", + "propertyValueCounter": 1, + "originArchived": false, + "description": null, + "modificationTime": 1549890959976, + "customizationUUID": "fceb3e8c-9100-4e1c-ba45-b9fe2dc18a2f", + "invariantName": "lb_1", + "componentName": "orit_vmme-nodes.heat.lbCvfc", + "sourceModelName": null, + "componentUid": "7937f019-b009-42bd-a523-bc751e590fed", + "componentVersion": "2.0", + "posX": 75.0, + "posY": 525.0 + }, + { + "uniqueId": "74f76b7d-1813-4436-97af-dc5bf6b63586.8a1d8169-d91f-4cb8-9af1-5c353dca2acf.mg_4", + "normalizedName": "mg_4", + "name": "mg_4", + "creationTime": 1549890959609, + "icon": "defaulticon", + "originType": "CVFC", + "propertyValueCounter": 1, + "originArchived": false, + "description": null, + "modificationTime": 1549890959976, + "customizationUUID": "475ab857-1fb4-476e-990b-1676bdd0b8be", + "invariantName": "mg_4", + "componentName": "orit_vmme-nodes.heat.mgCvfc", + "sourceModelName": null, + "componentUid": "8a1d8169-d91f-4cb8-9af1-5c353dca2acf", + "componentVersion": "2.0", + "posX": 275.0, + "posY": 725.0 + }, + { + "uniqueId": "74f76b7d-1813-4436-97af-dc5bf6b63586.8a1d8169-d91f-4cb8-9af1-5c353dca2acf.mg_422", + "normalizedName": "mg_4", + "name": "mg_4", + "creationTime": 1549890959609, + "icon": "defaulticon", + "originType": "CVFC", + "propertyValueCounter": 1, + "originArchived": false, + "description": null, + "modificationTime": 1549890959976, + "customizationUUID": "475ab857-1fb4-476e-990b-1676bdd0b8be", + "invariantName": "mg_4", + "componentName": "orit_vmme-nodes.heat.mgCvfc", + "sourceModelName": null, + "componentUid": "8a1d8169-d91f-4cb8-9af1-5c353dca2acf", + "componentVersion": "2.0", + "posX": 275.0, + "posY": 725.0 + } +] \ No newline at end of file diff --git a/catalog-ui/src/jest/mocks/groups.mock.ts b/catalog-ui/src/jest/mocks/groups.mock.ts new file mode 100644 index 0000000000..4b7f46ffa4 --- /dev/null +++ b/catalog-ui/src/jest/mocks/groups.mock.ts @@ -0,0 +1,44 @@ +export const groupsMock = [ + { + "uniqueId": "74f76b7d-1813-4436-97af-dc5bf6b63586.OritVmme..base_vepdg..module-0", + "name": "OritVmme..base_vepdg..module-0", + "type": "org.openecomp.groups.VfModule", + "members": { + "oam_1": "74f76b7d-1813-4436-97af-dc5bf6b63586.7c11da42-a7dc-47f2-8ac4-992f2d3cdc56.oam_1", + "lb_1": "74f76b7d-1813-4436-97af-dc5bf6b63586.7937f019-b009-42bd-a523-bc751e590fed.lb_1", + "dataFabric_int_net_id_RVN": "74f76b7d-1813-4436-97af-dc5bf6b63586.2a6cf1ea-6561-41f2-ae73-e1bdd0d1427d.datafabric_int_net_id_rvn", + "mg_4": "74f76b7d-1813-4436-97af-dc5bf6b63586.8a1d8169-d91f-4cb8-9af1-5c353dca2acf.mg_4", + "controlFabric_int_net_id_RVN": "74f76b7d-1813-4436-97af-dc5bf6b63586.2a6cf1ea-6561-41f2-ae73-e1bdd0d1427d.controlfabric_int_net_id_rvn", + "mg_3": "74f76b7d-1813-4436-97af-dc5bf6b63586.8a1d8169-d91f-4cb8-9af1-5c353dca2acf.mg_3" + } + }, + { + "uniqueId": "74f76b7d-1813-4436-97af-dc5bf6b63586.base_vepdg_volume_group", + "name": "base_vepdg_volume_group", + "type": "org.openecomp.groups.heat.HeatStack", + "members": { + + } + }, + { + "uniqueId": "74f76b7d-1813-4436-97af-dc5bf6b63586.vepdg_server_group_group", + "name": "vepdg_server_group_group", + "type": "tosca.groups.Root", + "members": { + + } + }, + { + "uniqueId": "74f76b7d-1813-4436-97af-dc5bf6b63586.base_vepdg_group", + "name": "base_vepdg_group", + "type": "org.openecomp.groups.heat.HeatStack", + "members": { + "oam_1": "74f76b7d-1813-4436-97af-dc5bf6b63586.7c11da42-a7dc-47f2-8ac4-992f2d3cdc56.oam_1", + "lb_1": "74f76b7d-1813-4436-97af-dc5bf6b63586.7937f019-b009-42bd-a523-bc751e590fed.lb_1", + "dataFabric_int_net_id_RVN": "74f76b7d-1813-4436-97af-dc5bf6b63586.2a6cf1ea-6561-41f2-ae73-e1bdd0d1427d.datafabric_int_net_id_rvn", + "mg_4": "74f76b7d-1813-4436-97af-dc5bf6b63586.8a1d8169-d91f-4cb8-9af1-5c353dca2acf.mg_4", + "controlFabric_int_net_id_RVN": "74f76b7d-1813-4436-97af-dc5bf6b63586.2a6cf1ea-6561-41f2-ae73-e1bdd0d1427d.controlfabric_int_net_id_rvn", + "mg_3": "74f76b7d-1813-4436-97af-dc5bf6b63586.8a1d8169-d91f-4cb8-9af1-5c353dca2acf.mg_3" + } + } +] \ No newline at end of file diff --git a/catalog-ui/src/jest/mocks/left-paeltte-elements.mock.ts b/catalog-ui/src/jest/mocks/left-paeltte-elements.mock.ts new file mode 100644 index 0000000000..c8b091e18d --- /dev/null +++ b/catalog-ui/src/jest/mocks/left-paeltte-elements.mock.ts @@ -0,0 +1,149 @@ +export const leftPaletteElements = + { + Generic: { + Network : [ + { + allVersions: { + 1.0: "1a55456f-3842-494c-873c-1a49e8e1c8a8", + 2.0: "145ac05a-2ae9-4bde-a719-30278ab6e011", + 3.0: "6c4c3614-101a-4d6a-b79b-9f76241b4ee1", + 3.1: "f667dcb2-7388-477a-8838-847a948ce2b7" + }, + categoryType: "COMPONENT", + certifiedIconClass: "", + componentSubType: "CP", + componentType: "RESOURCE", + displayName: "extVirtualMachineInterfaceCP", + iconName: "network", + invariantUUID: "e1d111f6-ee55-48fa-8b09-3535eb10185d", + isDraggable: true, + mainCategory: "Generic", + name: "extVirtualMachineInterfaceCP", + searchFilterTerms: "extvirtualmachineinterfacecp external port for virtual machine interface extvirtualmachineinterfacecp 3.0", + subCategory: "Network Elements", + systemName: "Extvirtualmachineinterfacecp", + uniqueId: "6c4c3614-101a-4d6a-b79b-9f76241b4ee1", + uuid: "9df6a0b9-9b13-4b70-9e2a-c5f4b93b56cf", + version: "3.0" + }, + { + allVersions: undefined, + categoryType: "COMPONENT", + certifiedIconClass: "non-certified", + componentSubType: "ServiceProxy", + componentType: "SERVICE", + displayName: "NewService2", + iconName: "defaulticon", + invariantUUID: "be13db98-2579-4780-9e40-04a5f7937723", + isDraggable: true, + mainCategory: "Generic", + name: "NewService2", + searchFilterTerms: "newservice2 asdfasdfa newservice2 0.3", + subCategory: "Generic", + systemName: "Newservice2", + uniqueId: "262198c2-04ea-4674-9cfe-c601b12f7961", + uuid: "2cf8baed-7ff9-4faf-9f41-b9f48e3ee435", + version: "0.3" + }, + { + allVersions: { + 1.0: "025840e6-7e8b-4be0-940a-aca3f64ac218", + 2.0: "84a05a83-8c8c-48bd-81c7-165fd8a4b631", + 3.0: "d4d5215c-e658-43db-95c6-1bfbafdae259", + 4.0: "5db22a16-029a-4bf7-a9ef-7ceda81f6edb", + 5.0: "86e6a636-a7b4-4392-8501-2857e6ba1d8b", + 6.0: "9a55a9c9-9e30-4077-8e92-6dcf69b250de", + 7.0: "eb515043-a771-4f84-92ea-ef15586f99be", + 8.0: "3d83195f-e92b-4f43-a821-f7043b107615", + 9.0: "a31ab521-b500-41f5-a20b-6d51f1cdff34" + }, + categoryType: "COMPONENT", + certifiedIconClass: "", + componentSubType: "Configuration", + componentType: "RESOURCE", + displayName: "VRF Entry Configuration", + iconName: "pmc", + invariantUUID: "0845cd3a-cdbc-46fc-aee3-b227fbeeb9ec", + isDraggable: true, + mainCategory: "Configuration", + name: "VRF Entry Configuration", + searchFilterTerms: "vrf entry configuration vrf entry configuration object vrf entry configuration 9.0", + subCategory: "Configuration", + systemName: "VrfEntryConfiguration", + uniqueId: "a31ab521-b500-41f5-a20b-6d51f1cdff34", + uuid: "4cd57279-54d5-4971-b744-96925649dac4", + version: "9.0" + }, + { + allVersions: { + 1.0: "9c829122-af05-4bc9-b537-5d84f4c8ae25", + 1.1: "930d56cb-868d-4e35-bd0f-e737d2fdb171" + }, + categoryType: "COMPONENT", + certifiedIconClass: "", + componentSubType: "VF", + componentType: "RESOURCE", + displayName: "sssssss", + iconName: "defaulticon", + invariantUUID: "34715c1c-fc70-46b2-99f0-b46a9fe4689d", + isDraggable: true, + mainCategory: "DCAE Component", + name: "sssssss", + searchFilterTerms: "sssssss sadfdsa sssssss 1.0", + subCategory: "Collector", + systemName: "Sssssss", + uniqueId: "9c829122-af05-4bc9-b537-5d84f4c8ae25", + uuid: "a8cf015e-e4e5-4d4b-a01e-8624e8d36095", + version: "1.0" + }, + { + allVersions: { + 1.0: "9c829122-af05-4bc9-b537-5d84f4c8ae25", + 1.1: "930d56cb-868d-4e35-bd0f-e737d2fdb171" + }, + categoryType: "GROUP", + certifiedIconClass: "", + componentSubType: "VF", + componentType: "RESOURCE", + displayName: "sssssss", + iconName: "defaulticon", + invariantUUID: "34715c1c-fc70-46b2-99f0-b46a9fe4689d", + isDraggable: true, + mainCategory: "DCAE Component", + name: "sssssss", + searchFilterTerms: "testVal and other values", + subCategory: "Collector", + systemName: "Sssssss", + uniqueId: "9c829122-af05-4bc9-b537-5d84f4c8ae25", + uuid: "a8cf015e-e4e5-4d4b-a01e-8624e8d36095", + version: "1.0" + } + ], + Configuration: [ + { + allVersions: { + 1.0: "1a55456f-3842-494c-873c-1a49e8e1c8a8", + 2.0: "145ac05a-2ae9-4bde-a719-30278ab6e011", + 3.0: "6c4c3614-101a-4d6a-b79b-9f76241b4ee1", + 3.1: "f667dcb2-7388-477a-8838-847a948ce2b7" + }, + categoryType: "COMPONENT", + certifiedIconClass: "", + componentSubType: "CP", + componentType: "RESOURCE", + displayName: "extVirtualMachineInterfaceCP", + iconName: "network", + invariantUUID: "e1d111f6-ee55-48fa-8b09-3535eb10185d", + isDraggable: true, + mainCategory: "Configuration", + name: "extVirtualMachineInterfaceCP", + searchFilterTerms: "extvirtualmachineinterfacecp external port for virtual machine interface extvirtualmachineinterfacecp 3.0", + subCategory: "Network Elements", + systemName: "Extvirtualmachineinterfacecp", + uniqueId: "6c4c3614-101a-4d6a-b79b-9f76241b4ee1", + uuid: "9df6a0b9-9b13-4b70-9e2a-c5f4b93b56cf", + version: "3.0" + }, + ] + } + }; diff --git a/catalog-ui/src/jest/mocks/onboarding-vsp.mock.ts b/catalog-ui/src/jest/mocks/onboarding-vsp.mock.ts new file mode 100644 index 0000000000..ff8a557800 --- /dev/null +++ b/catalog-ui/src/jest/mocks/onboarding-vsp.mock.ts @@ -0,0 +1,20 @@ +export const onboardingModalUniqueVSPMock = [ + {"name": "test new vsp", "vendorName": "test vlm", "categories": [{"name": "Network Connectivity", "subcategories": + [{"name": "Virtual Links"}]}], "csarVersion": "1.0", "csarUUID": "6348841e79a64871ba064ce340a968a4", "packageId": "6348841e79a64871ba064ce340a968a4", "description": "test new vsp description"}, + {"name": "new vsp2", "vendorName": "TestVSP", "categories": [{"name": "Network L2-3", "subcategories": [{"name": "WAN Connectors"}]}], + "csarVersion": "2.0", "csarUUID": "6348841e79a64871ba064ce340a968b5", "packageId": "abeb7b0c5fe04603b3236308f5eb8add", "description": "new vsp2 description"} +]; + +export const onboardingModalVSPMock = [ + {"name": "test new vsp", "vendorName": "test vlm", "categories": [{"name": "Network Connectivity", "subcategories": + [{"name": "Virtual Links"}]}], "csarVersion": "1.0", "csarUUID": "6348841e79a64871ba064ce340a968a4", "packageId": "6348841e79a64871ba064ce340a968a4", "description": "test new vsp description"}, + {"name": "new vsp2", "vendorName": "TestVSP", "categories": [{"name": "Network L2-3", "subcategories": [{"name": "WAN Connectors"}]}], + "csarVersion": "2.0", "csarUUID": "6348841e79a64871ba064ce340a968b5", "packageId": "abeb7b0c5fe04603b3236308f5eb8add", "description": "new vsp2 description"}, + {"name": "new vsp3", "vendorName": "TestVSP3", "categories": [{"name": "Network L2-3", "subcategories": [{"name": "WAN Connectors"}]}], + "csarVersion": "3.0", "csarUUID": "6348841e79a64871ba064ce340a968b6", "packageId": "abeb7b0c5fe04603b3236308f5eb8add", "description": "new vsp2 description"} +]; + +export const vspFromServerMock = {"name": "test new vsp22", "vendorName": "test vlm", "categories": [{"name": "Network Connectivity", "subcategories": + [{"name": "Virtual Links"}]}], "csarVersion": "1.0", "csarUUID": "6348841e79a64871ba064ce340a968a4", "packageId": "6348841e79a64871ba064ce340a968a4", + "description": "test new vsp description", "normalizedName": "testnewvsp22", "lifecycleState": "NOT_CERTIFIED_CHECKIN", + "creatorFullName": "Carlos Santana", "uuid": "ee1bc1e9-78f5-46b4-be14-273c3a8e9cfa", "version": "0.2", "lastUpdaterFullName": "Carlos Santana"}; diff --git a/catalog-ui/src/jest/mocks/req-and-capabilities.mock.ts b/catalog-ui/src/jest/mocks/req-and-capabilities.mock.ts new file mode 100644 index 0000000000..467f00d491 --- /dev/null +++ b/catalog-ui/src/jest/mocks/req-and-capabilities.mock.ts @@ -0,0 +1,30 @@ +import {Requirement} from "../../app/models/requirement"; + +export const requirementMock = [ + {"name": "dependency", "capability": "tosca.capabilities.Node", "node": "tosca.nodes.Root", "relationship": "tosca.relationships.DependsOn", "minOccurrences": "0", "maxOccurrences": "UNBOUNDED"}, + {"name": "binding", "capability": "tosca.capabilities.network.Bindable", "node": null, "relationship": "tosca.relationships.network.BindsTo", "minOccurrences": "1", "maxOccurrences": "UNBOUNDED"}, + {"name": "link", "capability": "tosca.capabilities.network.Linkable", "node": null, "relationship": "tosca.relationships.network.LinksTo", "minOccurrences": "1", "maxOccurrences": "UNBOUNDED"} +]; + +export const capabilitiesMock = [ + {"name": "attachment", "type": "tosca.capabilities.Attachment", "validSourceTypes": ["firstSource", "secondSource"], "minOccurrences": "0", "maxOccurrences": "UNBOUNDED"}, + {"name": "binding", "type": "tosca.capabilities.Node", "validSourceTypes": ["1source"], "minOccurrences": "1", "maxOccurrences": "UNBOUNDED"} +]; + +const requirement1: Requirement = new Requirement(); +requirement1.name = "dependency"; +requirement1.capability = "tosca.capabilities.Node"; +requirement1.node = "tosca.nodes.Root"; +requirement1.relationship = "tosca.relationships.DependsOn"; +requirement1.minOccurrences = "0"; +requirement1.maxOccurrences = "UNBOUNDED"; +const requirement2: Requirement = new Requirement(); +requirement2.name = "binding"; +requirement2.capability = "tosca.capabilities.network.Bindable"; +requirement2.node = null; +requirement2.relationship = "tosca.relationships.network.BindsTo"; +requirement2.minOccurrences = "1"; +requirement2.maxOccurrences = "UNBOUNDED"; +export const filterRequirmentsMock: Array = [requirement1, requirement2]; + + diff --git a/catalog-ui/src/jest/mocks/sdc-menu.mock.ts b/catalog-ui/src/jest/mocks/sdc-menu.mock.ts new file mode 100644 index 0000000000..57e76b6aec --- /dev/null +++ b/catalog-ui/src/jest/mocks/sdc-menu.mock.ts @@ -0,0 +1,7 @@ +export const sdcMenu = { + statuses: { + certified: {name: 'Certified', values: ['CERTIFIED']}, + distributed: {name: 'Distributed', values: ['DISTRIBUTED']}, + inDesign: {name: 'In Design', values: ['NOT_CERTIFIED_CHECKOUT', 'NOT_CERTIFIED_CHECKIN']} + } +}; diff --git a/catalog-ui/src/jest/mocks/service-metadata.mock.ts b/catalog-ui/src/jest/mocks/service-metadata.mock.ts new file mode 100644 index 0000000000..b3d6f952d7 --- /dev/null +++ b/catalog-ui/src/jest/mocks/service-metadata.mock.ts @@ -0,0 +1,40 @@ +export const serviceMetadata = { + "uniqueId": "3e39c1d2-8afb-4249-9950-110ec6e6f595", + "name": "fsdsfdsfd", + "version": "0.1", + "isHighestVersion": true, + "creationDate": 1538643760028, + "lastUpdateDate": 1538921966136, + "description": "vavs", + "lifecycleState": "NOT_CERTIFIED_CHECKIN", + "tags": [ + "fsdsfdsfd" + ], + "icon": "network_l_4", + "normalizedName": "fsdsfdsfd", + "systemName": "Fsdsfdsfd", + "contactId": "cs0008", + "allVersions": { + "0.1": "3e39c1d2-8afb-4249-9950-110ec6e6f595" + }, + "isDeleted": null, + "serviceFunction": "vassavsva", + "csarUUID": null, + "csarVersion": null, + "importedToscaChecksum": null, + "invariantUUID": "ad9f3ebc-fc59-4c24-bd3d-2eecd55a854d", + "componentType": "SERVICE", + "categories": [ + { + "name": "Network L4+", + "normalizedName": "network l4+", + "uniqueId": "serviceNewCategory.network l4+", + "icons": null, + "subcategories": null, + "version": null, + "ownerId": null, + "empty": false, + "type": null + } + ] +} \ No newline at end of file diff --git a/catalog-ui/src/jest/setup-jest.ts b/catalog-ui/src/jest/setup-jest.ts new file mode 100644 index 0000000000..60d9803b48 --- /dev/null +++ b/catalog-ui/src/jest/setup-jest.ts @@ -0,0 +1,3 @@ +import '../../node_modules/jest-preset-angular'; +import './jest-global-mocks'; +import 'jest-dom/extend-expect'; \ No newline at end of file diff --git a/catalog-ui/src/jest/test-config.helper.ts b/catalog-ui/src/jest/test-config.helper.ts new file mode 100644 index 0000000000..9ca9179c67 --- /dev/null +++ b/catalog-ui/src/jest/test-config.helper.ts @@ -0,0 +1,21 @@ +import { TestBed } from '@angular/core/testing' + +type CompilerOptions = Partial<{ + providers: any[] + useJit: boolean + preserveWhitespaces: boolean +}> +export type ConfigureFn = (testBed: typeof TestBed) => void + +export const configureTests = (configure: ConfigureFn, compilerOptions: CompilerOptions = {}) => { + const compilerConfig: CompilerOptions = { + preserveWhitespaces: false, + ...compilerOptions, + }; + + const configuredTestBed = TestBed.configureCompiler(compilerConfig); + + configure(configuredTestBed); + + return configuredTestBed.compileComponents().then(() => configuredTestBed) +}; \ No newline at end of file diff --git a/catalog-ui/src/polyfills.ts b/catalog-ui/src/polyfills.ts index 59846fce92..e39130fbfe 100644 --- a/catalog-ui/src/polyfills.ts +++ b/catalog-ui/src/polyfills.ts @@ -39,6 +39,7 @@ import 'core-js/es7/reflect'; import 'zone.js/dist/zone'; + // If you need to support the browsers/features below, uncomment the import // and run `npm install import-name-here'; // Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html diff --git a/catalog-ui/src/styles.less b/catalog-ui/src/styles.less index 795845e5fa..2dbaca5ad1 100644 --- a/catalog-ui/src/styles.less +++ b/catalog-ui/src/styles.less @@ -7,5 +7,6 @@ @import '../node_modules/angular-resizable/angular-resizable.min.css'; @import '../node_modules/angular-tooltips/dist/angular-tooltips.min.css'; @import '../node_modules/animate.css/animate.min.css'; +@import '../node_modules/onap-ui-common/lib/style.css'; @import './assets/styles/app.less'; diff --git a/catalog-ui/src/tsconfig.json b/catalog-ui/src/tsconfig.json index 9a4c6bbf0f..81d527b763 100644 --- a/catalog-ui/src/tsconfig.json +++ b/catalog-ui/src/tsconfig.json @@ -13,6 +13,11 @@ "es6", "dom" ], + "paths": { + "@angular/*": [ + "../node_modules/@angular/*" + ] + }, "sourceMap": true, "target": "es5", "typeRoots": [ @@ -20,14 +25,12 @@ "./typings" ], "types": [ - "jquery", "core-js", - "node" + "node", + "jest" ], "forceConsistentCasingInFileNames": true }, "exclude": [ - "test.ts", - "**/*.spec.ts" ] } \ No newline at end of file diff --git a/catalog-ui/src/tsconfig.spec.json b/catalog-ui/src/tsconfig.spec.json new file mode 100644 index 0000000000..24cfb7ae35 --- /dev/null +++ b/catalog-ui/src/tsconfig.spec.json @@ -0,0 +1,24 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "allowJs": true, + "outDir": "../out-tsc/spec", + "module": "commonjs", + "target": "es5", + "emitDecoratorMetadata": true, + "lib": [ "es2015" ], + "baseUrl": ".", + "types": [ + "jest", + "node" + ] + }, + "files": [ + "polyfills.ts" + ], + "include": [ + "**/*.spec.ts", + "**/*.d.ts" + ] + +} \ No newline at end of file diff --git a/catalog-ui/src/typings/angularjs/angular.d.ts b/catalog-ui/src/typings/angularjs/angular.d.ts index 36d68e18a2..c0cb9d9890 100644 --- a/catalog-ui/src/typings/angularjs/angular.d.ts +++ b/catalog-ui/src/typings/angularjs/angular.d.ts @@ -23,7 +23,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// declare var angular: angular.IAngularStatic; diff --git a/catalog-ui/src/typings/jasmine/jasmine.d.ts b/catalog-ui/src/typings/jasmine/jasmine.d.ts deleted file mode 100644 index 99ccb91fed..0000000000 --- a/catalog-ui/src/typings/jasmine/jasmine.d.ts +++ /dev/null @@ -1,515 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -// Type definitions for Jasmine 2.2 -// Project: http://jasmine.github.io/ -// Definitions by: Boris Yankov , Theodore Brown , David Pärsson -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -// For ddescribe / iit use : https://github.com/borisyankov/DefinitelyTyped/blob/master/karma-jasmine/karma-jasmine.d.ts - -declare function describe(description: string, specDefinitions: () => void): void; -declare function fdescribe(description: string, specDefinitions: () => void): void; -declare function xdescribe(description: string, specDefinitions: () => void): void; - -declare function it(expectation: string, assertion?: () => void, timeout?: number): void; -declare function it(expectation: string, assertion?: (done: () => void) => void, timeout?: number): void; -declare function fit(expectation: string, assertion?: () => void, timeout?: number): void; -declare function fit(expectation: string, assertion?: (done: () => void) => void, timeout?: number): void; -declare function xit(expectation: string, assertion?: () => void, timeout?: number): void; -declare function xit(expectation: string, assertion?: (done: () => void) => void, timeout?: number): void; - -/** If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. */ -declare function pending(reason?: string): void; - -declare function beforeEach(action: () => void, timeout?: number): void; -declare function beforeEach(action: (done: () => void) => void, timeout?: number): void; -declare function afterEach(action: () => void, timeout?: number): void; -declare function afterEach(action: (done: () => void) => void, timeout?: number): void; - -declare function beforeAll(action: () => void, timeout?: number): void; -declare function beforeAll(action: (done: () => void) => void, timeout?: number): void; -declare function afterAll(action: () => void, timeout?: number): void; -declare function afterAll(action: (done: () => void) => void, timeout?: number): void; - -declare function expect(spy: Function): jasmine.Matchers; -declare function expect(actual: any): jasmine.Matchers; - -declare function fail(e?: any): void; - -declare function spyOn(object: any, method: string): jasmine.Spy; - -declare function runs(asyncMethod: Function): void; -declare function waitsFor(latchMethod: () => boolean, failureMessage?: string, timeout?: number): void; -declare function waits(timeout?: number): void; - -declare module jasmine { - - var clock: () => Clock; - - function any(aclass: any): Any; - function anything(): Any; - function arrayContaining(sample: any[]): ArrayContaining; - function objectContaining(sample: any): ObjectContaining; - function createSpy(name: string, originalFn?: Function): Spy; - function createSpyObj(baseName: string, methodNames: any[]): any; - function createSpyObj(baseName: string, methodNames: any[]): T; - function pp(value: any): string; - function getEnv(): Env; - function addCustomEqualityTester(equalityTester: CustomEqualityTester): void; - function addMatchers(matchers: CustomMatcherFactories): void; - function stringMatching(str: string): Any; - function stringMatching(str: RegExp): Any; - - interface Any { - - new (expectedClass: any): any; - - jasmineMatches(other: any): boolean; - jasmineToString(): string; - } - - // taken from TypeScript lib.core.es6.d.ts, applicable to CustomMatchers.contains() - interface ArrayLike { - length: number; - [n: number]: T; - } - - interface ArrayContaining { - new (sample: any[]): any; - - asymmetricMatch(other: any): boolean; - jasmineToString(): string; - } - - interface ObjectContaining { - new (sample: any): any; - - jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean; - jasmineToString(): string; - } - - interface Block { - - new (env: Env, func: SpecFunction, spec: Spec): any; - - execute(onComplete: () => void): void; - } - - interface WaitsBlock extends Block { - new (env: Env, timeout: number, spec: Spec): any; - } - - interface WaitsForBlock extends Block { - new (env: Env, timeout: number, latchFunction: SpecFunction, message: string, spec: Spec): any; - } - - interface Clock { - install(): void; - uninstall(): void; - /** Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds. */ - tick(ms: number): void; - mockDate(date?: Date): void; - } - - interface CustomEqualityTester { - (first: any, second: any): boolean; - } - - interface CustomMatcher { - compare(actual: T, expected: T): CustomMatcherResult; - compare(actual: any, expected: any): CustomMatcherResult; - } - - interface CustomMatcherFactory { - (util: MatchersUtil, customEqualityTesters: Array): CustomMatcher; - } - - interface CustomMatcherFactories { - [index: string]: CustomMatcherFactory; - } - - interface CustomMatcherResult { - pass: boolean; - message: string; - } - - interface MatchersUtil { - equals(a: any, b: any, customTesters?: Array): boolean; - contains(haystack: ArrayLike | string, needle: any, customTesters?: Array): boolean; - buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array): string; - } - - interface Env { - setTimeout: any; - clearTimeout: void; - setInterval: any; - clearInterval: void; - updateInterval: number; - - currentSpec: Spec; - - matchersClass: Matchers; - - version(): any; - versionString(): string; - nextSpecId(): number; - addReporter(reporter: Reporter): void; - execute(): void; - describe(description: string, specDefinitions: () => void): Suite; - // ddescribe(description: string, specDefinitions: () => void): Suite; Not a part of jasmine. Angular team adds these - beforeEach(beforeEachFunction: () => void): void; - beforeAll(beforeAllFunction: () => void): void; - currentRunner(): Runner; - afterEach(afterEachFunction: () => void): void; - afterAll(afterAllFunction: () => void): void; - xdescribe(desc: string, specDefinitions: () => void): XSuite; - it(description: string, func: () => void): Spec; - // iit(description: string, func: () => void): Spec; Not a part of jasmine. Angular team adds these - xit(desc: string, func: () => void): XSpec; - compareRegExps_(a: RegExp, b: RegExp, mismatchKeys: string[], mismatchValues: string[]): boolean; - compareObjects_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; - equals_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; - contains_(haystack: any, needle: any): boolean; - addCustomEqualityTester(equalityTester: CustomEqualityTester): void; - addMatchers(matchers: CustomMatcherFactories): void; - specFilter(spec: Spec): boolean; - } - - interface FakeTimer { - - new (): any; - - reset(): void; - tick(millis: number): void; - runFunctionsWithinRange(oldMillis: number, nowMillis: number): void; - scheduleFunction(timeoutKey: any, funcToCall: () => void, millis: number, recurring: boolean): void; - } - - interface HtmlReporter { - new (): any; - } - - interface HtmlSpecFilter { - new (): any; - } - - interface Result { - type: string; - } - - interface NestedResults extends Result { - description: string; - - totalCount: number; - passedCount: number; - failedCount: number; - - skipped: boolean; - - rollupCounts(result: NestedResults): void; - log(values: any): void; - getItems(): Result[]; - addResult(result: Result): void; - passed(): boolean; - } - - interface MessageResult extends Result { - values: any; - trace: Trace; - } - - interface ExpectationResult extends Result { - matcherName: string; - passed(): boolean; - expected: any; - actual: any; - message: string; - trace: Trace; - } - - interface Trace { - name: string; - message: string; - stack: any; - } - - interface PrettyPrinter { - - new (): any; - - format(value: any): void; - iterateObject(obj: any, fn: (property: string, isGetter: boolean) => void): void; - emitScalar(value: any): void; - emitString(value: string): void; - emitArray(array: any[]): void; - emitObject(obj: any): void; - append(value: any): void; - } - - interface StringPrettyPrinter extends PrettyPrinter { - } - - interface Queue { - - new (env: any): any; - - env: Env; - ensured: boolean[]; - blocks: Block[]; - running: boolean; - index: number; - offset: number; - abort: boolean; - - addBefore(block: Block, ensure?: boolean): void; - add(block: any, ensure?: boolean): void; - insertNext(block: any, ensure?: boolean): void; - start(onComplete?: () => void): void; - isRunning(): boolean; - next_(): void; - results(): NestedResults; - } - - interface Matchers { - - new (env: Env, actual: any, spec: Env, isNot?: boolean): any; - - env: Env; - actual: any; - spec: Env; - isNot?: boolean; - message(): any; - - toBe(expected: any, expectationFailOutput?: any): boolean; - toEqual(expected: any, expectationFailOutput?: any): boolean; - toMatch(expected: any, expectationFailOutput?: any): boolean; - toBeDefined(expectationFailOutput?: any): boolean; - toBeUndefined(expectationFailOutput?: any): boolean; - toBeNull(expectationFailOutput?: any): boolean; - toBeNaN(): boolean; - toBeTruthy(expectationFailOutput?: any): boolean; - toBeFalsy(expectationFailOutput?: any): boolean; - toHaveBeenCalled(): boolean; - toHaveBeenCalledWith(...params: any[]): boolean; - toContain(expected: any, expectationFailOutput?: any): boolean; - toBeLessThan(expected: any, expectationFailOutput?: any): boolean; - toBeGreaterThan(expected: any, expectationFailOutput?: any): boolean; - toBeCloseTo(expected: any, precision: any, expectationFailOutput?: any): boolean; - toContainHtml(expected: string): boolean; - toContainText(expected: string): boolean; - toThrow(expected?: any): boolean; - toThrowError(expected?: any, message?: string): boolean; - not: Matchers; - - Any: Any; - } - - interface Reporter { - reportRunnerStarting(runner: Runner): void; - reportRunnerResults(runner: Runner): void; - reportSuiteResults(suite: Suite): void; - reportSpecStarting(spec: Spec): void; - reportSpecResults(spec: Spec): void; - log(str: string): void; - } - - interface MultiReporter extends Reporter { - addReporter(reporter: Reporter): void; - } - - interface Runner { - - new (env: Env): any; - - execute(): void; - beforeEach(beforeEachFunction: SpecFunction): void; - afterEach(afterEachFunction: SpecFunction): void; - beforeAll(beforeAllFunction: SpecFunction): void; - afterAll(afterAllFunction: SpecFunction): void; - finishCallback(): void; - addSuite(suite: Suite): void; - add(block: Block): void; - specs(): Spec[]; - suites(): Suite[]; - topLevelSuites(): Suite[]; - results(): NestedResults; - } - - interface SpecFunction { - (spec?: Spec): void; - } - - interface SuiteOrSpec { - id: number; - env: Env; - description: string; - queue: Queue; - } - - interface Spec extends SuiteOrSpec { - - new (env: Env, suite: Suite, description: string): any; - - suite: Suite; - - afterCallbacks: SpecFunction[]; - spies_: Spy[]; - - results_: NestedResults; - matchersClass: Matchers; - - getFullName(): string; - results(): NestedResults; - log(arguments: any): any; - runs(func: SpecFunction): Spec; - addToQueue(block: Block): void; - addMatcherResult(result: Result): void; - expect(actual: any): any; - waits(timeout: number): Spec; - waitsFor(latchFunction: SpecFunction, timeoutMessage?: string, timeout?: number): Spec; - fail(e?: any): void; - getMatchersClass_(): Matchers; - addMatchers(matchersPrototype: CustomMatcherFactories): void; - finishCallback(): void; - finish(onComplete?: () => void): void; - after(doAfter: SpecFunction): void; - execute(onComplete?: () => void): any; - addBeforesAndAftersToQueue(): void; - explodes(): void; - spyOn(obj: any, methodName: string, ignoreMethodDoesntExist: boolean): Spy; - removeAllSpies(): void; - } - - interface XSpec { - id: number; - runs(): void; - } - - interface Suite extends SuiteOrSpec { - - new (env: Env, description: string, specDefinitions: () => void, parentSuite: Suite): any; - - parentSuite: Suite; - - getFullName(): string; - finish(onComplete?: () => void): void; - beforeEach(beforeEachFunction: SpecFunction): void; - afterEach(afterEachFunction: SpecFunction): void; - beforeAll(beforeAllFunction: SpecFunction): void; - afterAll(afterAllFunction: SpecFunction): void; - results(): NestedResults; - add(suiteOrSpec: SuiteOrSpec): void; - specs(): Spec[]; - suites(): Suite[]; - children(): any[]; - execute(onComplete?: () => void): void; - } - - interface XSuite { - execute(): void; - } - - interface Spy { - (...params: any[]): any; - - identity: string; - and: SpyAnd; - calls: Calls; - mostRecentCall: { args: any[]; }; - argsForCall: any[]; - wasCalled: boolean; - } - - interface SpyAnd { - /** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */ - callThrough(): Spy; - /** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */ - returnValue(val: any): void; - /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */ - callFake(fn: Function): Spy; - /** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */ - throwError(msg: string): void; - /** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */ - stub(): Spy; - } - - interface Calls { - /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. **/ - any(): boolean; - /** By chaining the spy with calls.count(), will return the number of times the spy was called **/ - count(): number; - /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index **/ - argsFor(index: number): any[]; - /** By chaining the spy with calls.allArgs(), will return the arguments to all calls **/ - allArgs(): any[]; - /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls **/ - all(): CallInfo[]; - /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call **/ - mostRecent(): CallInfo; - /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call **/ - first(): CallInfo; - /** By chaining the spy with calls.reset(), will clears all tracking for a spy **/ - reset(): void; - } - - interface CallInfo { - /** The context (the this) for the call */ - object: any; - /** All arguments passed to the call */ - args: any[]; - } - - interface Util { - inherit(childClass: Function, parentClass: Function): any; - formatException(e: any): any; - htmlEscape(str: string): string; - argsToArray(args: any): any; - extend(destination: any, source: any): any; - } - - interface JsApiReporter extends Reporter { - - started: boolean; - finished: boolean; - result: any; - messages: any; - - new (): any; - - suites(): Suite[]; - summarize_(suiteOrSpec: SuiteOrSpec): any; - results(): any; - resultsForSpec(specId: any): any; - log(str: any): any; - resultsForSpecs(specIds: any): any; - summarizeResult_(result: any): any; - } - - interface Jasmine { - Spec: Spec; - clock: Clock; - util: Util; - } - - export var HtmlReporter: HtmlReporter; - export var HtmlSpecFilter: HtmlSpecFilter; - export var DEFAULT_TIMEOUT_INTERVAL: number; -} diff --git a/catalog-ui/src/typings/jquery/jquery.d.ts b/catalog-ui/src/typings/jquery/jquery.d.ts deleted file mode 100644 index cc20de588b..0000000000 --- a/catalog-ui/src/typings/jquery/jquery.d.ts +++ /dev/null @@ -1,3181 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -// Type definitions for jQuery 1.10.x / 2.0.x -// Project: http://jquery.com/ -// Definitions by: Boris Yankov , Christian Hoffmeister , Steve Fenton , Diullei Gomes , Tass Iliopoulos , Jason Swearingen , Sean Hill , Guus Goossens , Kelly Summerlin , Basarat Ali Syed , Nicholas Wolverson , Derek Cicerone , Andrew Gaspar , James Harrison Fisher , Seikichi Kondo , Benjamin Jackman , Poul Sorensen , Josh Strobl , John Reilly , Dick van den Brink -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/* ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - - -/** - * Interface for the AJAX setting that will configure the AJAX request - */ -interface JQueryAjaxSettings { - /** - * The content type sent in the request header that tells the server what kind of response it will accept in return. If the accepts setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. - */ - accepts?: any; - /** - * By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success(). - */ - async?: boolean; - /** - * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request. - */ - beforeSend? (jqXHR: JQueryXHR, settings: JQueryAjaxSettings): any; - /** - * If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET. - */ - cache?: boolean; - /** - * A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. - */ - complete? (jqXHR: JQueryXHR, textStatus: string): any; - /** - * An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5) - */ - contents?: { [key: string]: any; }; - //According to jQuery.ajax source code, ajax's option actually allows contentType to set to "false" - // https://github.com/borisyankov/DefinitelyTyped/issues/742 - /** - * When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. - */ - contentType?: any; - /** - * This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). - */ - context?: any; - /** - * An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. (version added: 1.5) - */ - converters?: { [key: string]: any; }; - /** - * If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain. (version added: 1.5) - */ - crossDomain?: boolean; - /** - * Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). - */ - data?: any; - /** - * A function to be used to handle the raw response data of XMLHttpRequest.This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter. - */ - dataFilter? (data: any, ty: any): any; - /** - * The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). - */ - dataType?: string; - /** - * A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event. - */ - error? (jqXHR: JQueryXHR, textStatus: string, errorThrown: string): any; - /** - * Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events. - */ - global?: boolean; - /** - * An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function. (version added: 1.5) - */ - headers?: { [key: string]: any; }; - /** - * Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data. - */ - ifModified?: boolean; - /** - * Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. (version added: 1.5.1) - */ - isLocal?: boolean; - /** - * Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" } - */ - jsonp?: any; - /** - * Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function. - */ - jsonpCallback?: any; - /** - * A mime type to override the XHR mime type. (version added: 1.5.1) - */ - mimeType?: string; - /** - * A password to be used with XMLHttpRequest in response to an HTTP access authentication request. - */ - password?: string; - /** - * By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false. - */ - processData?: boolean; - /** - * Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or "script" dataType and "GET" type). Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script. - */ - scriptCharset?: string; - /** - * An object of numeric HTTP codes and functions to be called when the response has the corresponding code. f the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback. (version added: 1.5) - */ - statusCode?: { [key: string]: any; }; - /** - * A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. - */ - success? (data: any, textStatus: string, jqXHR: JQueryXHR): any; - /** - * Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period. - */ - timeout?: number; - /** - * Set this to true if you wish to use the traditional style of param serialization. - */ - traditional?: boolean; - /** - * The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers. - */ - type?: string; - /** - * A string containing the URL to which the request is sent. - */ - url?: string; - /** - * A username to be used with XMLHttpRequest in response to an HTTP access authentication request. - */ - username?: string; - /** - * Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory. - */ - xhr?: any; - /** - * An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed. In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it. (version added: 1.5.1) - */ - xhrFields?: { [key: string]: any; }; -} - -/** - * Interface for the jqXHR object - */ -interface JQueryXHR extends XMLHttpRequest, JQueryPromise { - /** - * The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header. As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). - */ - overrideMimeType(mimeType: string): any; - /** - * Cancel the request. - * - * @param statusText A string passed as the textStatus parameter for the done callback. Default value: "canceled" - */ - abort(statusText?: string): void; - /** - * Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details. - */ - then(doneCallback: (data: any, textStatus: string, jqXHR: JQueryXHR) => void, failCallback?: (jqXHR: JQueryXHR, textStatus: string, errorThrown: any) => void): JQueryPromise; - /** - * Property containing the parsed response if the response Content-Type is json - */ - responseJSON?: any; -} - -/** - * Interface for the JQuery callback - */ -interface JQueryCallback { - /** - * Add a callback or a collection of callbacks to a callback list. - * - * @param callbacks A function, or array of functions, that are to be added to the callback list. - */ - add(callbacks: Function): JQueryCallback; - /** - * Add a callback or a collection of callbacks to a callback list. - * - * @param callbacks A function, or array of functions, that are to be added to the callback list. - */ - add(callbacks: Function[]): JQueryCallback; - - /** - * Disable a callback list from doing anything more. - */ - disable(): JQueryCallback; - - /** - * Determine if the callbacks list has been disabled. - */ - disabled(): boolean; - - /** - * Remove all of the callbacks from a list. - */ - empty(): JQueryCallback; - - /** - * Call all of the callbacks with the given arguments - * - * @param arguments The argument or list of arguments to pass back to the callback list. - */ - fire(...arguments: any[]): JQueryCallback; - - /** - * Determine if the callbacks have already been called at least once. - */ - fired(): boolean; - - /** - * Call all callbacks in a list with the given context and arguments. - * - * @param context A reference to the context in which the callbacks in the list should be fired. - * @param arguments An argument, or array of arguments, to pass to the callbacks in the list. - */ - fireWith(context?: any, ...args: any[]): JQueryCallback; - - /** - * Determine whether a supplied callback is in a list - * - * @param callback The callback to search for. - */ - has(callback: Function): boolean; - - /** - * Lock a callback list in its current state. - */ - lock(): JQueryCallback; - - /** - * Determine if the callbacks list has been locked. - */ - locked(): boolean; - - /** - * Remove a callback or a collection of callbacks from a callback list. - * - * @param callbacks A function, or array of functions, that are to be removed from the callback list. - */ - remove(callbacks: Function): JQueryCallback; - /** - * Remove a callback or a collection of callbacks from a callback list. - * - * @param callbacks A function, or array of functions, that are to be removed from the callback list. - */ - remove(callbacks: Function[]): JQueryCallback; -} - -/** - * Allows jQuery Promises to interop with non-jQuery promises - */ -interface JQueryGenericPromise { - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter A function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - */ - then(doneFilter: (value?: T, ...values: any[]) => U|JQueryPromise, failFilter?: (...reasons: any[]) => any, progressFilter?: (...progression: any[]) => any): JQueryPromise; - - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter A function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - */ - then(doneFilter: (value?: T, ...values: any[]) => void, failFilter?: (...reasons: any[]) => any, progressFilter?: (...progression: any[]) => any): JQueryPromise; -} - -/** - * Interface for the JQuery promise/deferred callbacks - */ -interface JQueryPromiseCallback { - (value?: T, ...args: any[]): void; -} - -interface JQueryPromiseOperator { - (callback1: JQueryPromiseCallback|JQueryPromiseCallback[], ...callbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; -} - -/** - * Interface for the JQuery promise, part of callbacks - */ -interface JQueryPromise extends JQueryGenericPromise { - /** - * Determine the current state of a Deferred object. - */ - state(): string; - /** - * Add handlers to be called when the Deferred object is either resolved or rejected. - * - * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. - * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. - */ - always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; - /** - * Add handlers to be called when the Deferred object is resolved. - * - * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. - * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. - */ - done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; - /** - * Add handlers to be called when the Deferred object is rejected. - * - * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. - * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. - */ - fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; - /** - * Add handlers to be called when the Deferred object generates progress notifications. - * - * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. - */ - progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; - - // Deprecated - given no typings - pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; -} - -/** - * Interface for the JQuery deferred, part of callbacks - */ -interface JQueryDeferred extends JQueryGenericPromise { - /** - * Determine the current state of a Deferred object. - */ - state(): string; - /** - * Add handlers to be called when the Deferred object is either resolved or rejected. - * - * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. - * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. - */ - always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; - /** - * Add handlers to be called when the Deferred object is resolved. - * - * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. - * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. - */ - done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; - /** - * Add handlers to be called when the Deferred object is rejected. - * - * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. - * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. - */ - fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; - /** - * Add handlers to be called when the Deferred object generates progress notifications. - * - * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. - */ - progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; - - /** - * Call the progressCallbacks on a Deferred object with the given args. - * - * @param args Optional arguments that are passed to the progressCallbacks. - */ - notify(value?: any, ...args: any[]): JQueryDeferred; - - /** - * Call the progressCallbacks on a Deferred object with the given context and args. - * - * @param context Context passed to the progressCallbacks as the this object. - * @param args Optional arguments that are passed to the progressCallbacks. - */ - notifyWith(context: any, value?: any, ...args: any[]): JQueryDeferred; - - /** - * Reject a Deferred object and call any failCallbacks with the given args. - * - * @param args Optional arguments that are passed to the failCallbacks. - */ - reject(value?: any, ...args: any[]): JQueryDeferred; - /** - * Reject a Deferred object and call any failCallbacks with the given context and args. - * - * @param context Context passed to the failCallbacks as the this object. - * @param args An optional array of arguments that are passed to the failCallbacks. - */ - rejectWith(context: any, value?: any, ...args: any[]): JQueryDeferred; - - /** - * Resolve a Deferred object and call any doneCallbacks with the given args. - * - * @param value First argument passed to doneCallbacks. - * @param args Optional subsequent arguments that are passed to the doneCallbacks. - */ - resolve(value?: T, ...args: any[]): JQueryDeferred; - - /** - * Resolve a Deferred object and call any doneCallbacks with the given context and args. - * - * @param context Context passed to the doneCallbacks as the this object. - * @param args An optional array of arguments that are passed to the doneCallbacks. - */ - resolveWith(context: any, value?: T, ...args: any[]): JQueryDeferred; - - /** - * Return a Deferred's Promise object. - * - * @param target Object onto which the promise methods have to be attached - */ - promise(target?: any): JQueryPromise; - - // Deprecated - given no typings - pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; -} - -/** - * Interface of the JQuery extension of the W3C event object - */ -interface BaseJQueryEventObject extends Event { - data: any; - delegateTarget: Element; - isDefaultPrevented(): boolean; - isImmediatePropagationStopped(): boolean; - isPropagationStopped(): boolean; - namespace: string; - originalEvent: Event; - preventDefault(): any; - relatedTarget: Element; - result: any; - stopImmediatePropagation(): void; - stopPropagation(): void; - target: Element; - pageX: number; - pageY: number; - which: number; - metaKey: boolean; -} - -interface JQueryInputEventObject extends BaseJQueryEventObject { - altKey: boolean; - ctrlKey: boolean; - metaKey: boolean; - shiftKey: boolean; -} - -interface JQueryMouseEventObject extends JQueryInputEventObject { - button: number; - clientX: number; - clientY: number; - offsetX: number; - offsetY: number; - pageX: number; - pageY: number; - screenX: number; - screenY: number; -} - -interface JQueryKeyEventObject extends JQueryInputEventObject { - char: any; - charCode: number; - key: any; - keyCode: number; -} - -interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject{ -} - -/* - Collection of properties of the current browser -*/ - -interface JQuerySupport { - ajax?: boolean; - boxModel?: boolean; - changeBubbles?: boolean; - checkClone?: boolean; - checkOn?: boolean; - cors?: boolean; - cssFloat?: boolean; - hrefNormalized?: boolean; - htmlSerialize?: boolean; - leadingWhitespace?: boolean; - noCloneChecked?: boolean; - noCloneEvent?: boolean; - opacity?: boolean; - optDisabled?: boolean; - optSelected?: boolean; - scriptEval? (): boolean; - style?: boolean; - submitBubbles?: boolean; - tbody?: boolean; -} - -interface JQueryParam { - /** - * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. - * - * @param obj An array or object to serialize. - */ - (obj: any): string; - - /** - * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. - * - * @param obj An array or object to serialize. - * @param traditional A Boolean indicating whether to perform a traditional "shallow" serialization. - */ - (obj: any, traditional: boolean): string; -} - -/** - * The interface used to construct jQuery events (with $.Event). It is - * defined separately instead of inline in JQueryStatic to allow - * overriding the construction function with specific strings - * returning specific event objects. - */ -interface JQueryEventConstructor { - (name: string, eventProperties?: any): JQueryEventObject; - new (name: string, eventProperties?: any): JQueryEventObject; -} - -/** - * The interface used to specify coordinates. - */ -interface JQueryCoordinates { - left: number; - top: number; -} - -/** - * Elements in the array returned by serializeArray() - */ -interface JQuerySerializeArrayElement { - name: string; - value: string; -} - -interface JQueryAnimationOptions { - /** - * A string or number determining how long the animation will run. - */ - duration?: any; - /** - * A string indicating which easing function to use for the transition. - */ - easing?: string; - /** - * A function to call once the animation is complete. - */ - complete?: Function; - /** - * A function to be called for each animated property of each animated element. This function provides an opportunity to modify the Tween object to change the value of the property before it is set. - */ - step?: (now: number, tween: any) => any; - /** - * A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties. (version added: 1.8) - */ - progress?: (animation: JQueryPromise, progress: number, remainingMs: number) => any; - /** - * A function to call when the animation begins. (version added: 1.8) - */ - start?: (animation: JQueryPromise) => any; - /** - * A function to be called when the animation completes (its Promise object is resolved). (version added: 1.8) - */ - done?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; - /** - * A function to be called when the animation fails to complete (its Promise object is rejected). (version added: 1.8) - */ - fail?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; - /** - * A function to be called when the animation completes or stops without completing (its Promise object is either resolved or rejected). (version added: 1.8) - */ - always?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; - /** - * A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string. When a custom queue name is used the animation does not automatically start; you must call .dequeue("queuename") to start it. - */ - queue?: any; - /** - * A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions. (version added: 1.4) - */ - specialEasing?: Object; -} - -/** - * Static members of jQuery (those on $ and jQuery themselves) - */ -interface JQueryStatic { - - /** - * Perform an asynchronous HTTP (Ajax) request. - * - * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). - */ - ajax(settings: JQueryAjaxSettings): JQueryXHR; - /** - * Perform an asynchronous HTTP (Ajax) request. - * - * @param url A string containing the URL to which the request is sent. - * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). - */ - ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR; - - /** - * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). - * - * @param dataTypes An optional string containing one or more space-separated dataTypes - * @param handler A handler to set default values for future Ajax requests. - */ - ajaxPrefilter(dataTypes: string, handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; - /** - * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). - * - * @param handler A handler to set default values for future Ajax requests. - */ - ajaxPrefilter(handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; - - ajaxSettings: JQueryAjaxSettings; - - /** - * Set default values for future Ajax requests. Its use is not recommended. - * - * @param options A set of key/value pairs that configure the default Ajax request. All options are optional. - */ - ajaxSetup(options: JQueryAjaxSettings): void; - - /** - * Load data from the server using a HTTP GET request. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). - */ - get(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; - /** - * Load data from the server using a HTTP GET request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). - */ - get(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; - /** - * Load JSON-encoded data from the server using a GET HTTP request. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. - */ - getJSON(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; - /** - * Load JSON-encoded data from the server using a GET HTTP request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. - */ - getJSON(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; - /** - * Load a JavaScript file from the server using a GET HTTP request, then execute it. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. - */ - getScript(url: string, success?: (script: string, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; - - /** - * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. - */ - param: JQueryParam; - - /** - * Load data from the server using a HTTP POST request. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - */ - post(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; - /** - * Load data from the server using a HTTP POST request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - */ - post(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; - - /** - * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. - * - * @param flags An optional list of space-separated flags that change how the callback list behaves. - */ - Callbacks(flags?: string): JQueryCallback; - - /** - * Holds or releases the execution of jQuery's ready event. - * - * @param hold Indicates whether the ready hold is being requested or released - */ - holdReady(hold: boolean): void; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param selector A string containing a selector expression - * @param context A DOM Element, Document, or jQuery to use as context - */ - (selector: string, context?: Element|JQuery): JQuery; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param element A DOM element to wrap in a jQuery object. - */ - (element: Element): JQuery; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param elementArray An array containing a set of DOM elements to wrap in a jQuery object. - */ - (elementArray: Element[]): JQuery; - - /** - * Binds a function to be executed when the DOM has finished loading. - * - * @param callback A function to execute after the DOM is ready. - */ - (callback: (jQueryAlias?: JQueryStatic) => any): JQuery; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param object A plain object to wrap in a jQuery object. - */ - (object: {}): JQuery; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param object An existing jQuery object to clone. - */ - (object: JQuery): JQuery; - - /** - * Specify a function to execute when the DOM is fully loaded. - */ - (): JQuery; - - /** - * Creates DOM elements on the fly from the provided string of raw HTML. - * - * @param html A string of HTML to create on the fly. Note that this parses HTML, not XML. - * @param ownerDocument A document in which the new elements will be created. - */ - (html: string, ownerDocument?: Document): JQuery; - - /** - * Creates DOM elements on the fly from the provided string of raw HTML. - * - * @param html A string defining a single, standalone, HTML element (e.g.
    or
    ). - * @param attributes An object of attributes, events, and methods to call on the newly-created element. - */ - (html: string, attributes: Object): JQuery; - - /** - * Relinquish jQuery's control of the $ variable. - * - * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). - */ - noConflict(removeAll?: boolean): Object; - - /** - * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. - * - * @param deferreds One or more Deferred objects, or plain JavaScript objects. - */ - when(...deferreds: Array/* as JQueryDeferred */>): JQueryPromise; - - /** - * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties. - */ - cssHooks: { [key: string]: any; }; - cssNumber: any; - - /** - * Store arbitrary data associated with the specified element. Returns the value that was set. - * - * @param element The DOM element to associate with the data. - * @param key A string naming the piece of data to set. - * @param value The new data value. - */ - data(element: Element, key: string, value: T): T; - /** - * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. - * - * @param element The DOM element to associate with the data. - * @param key A string naming the piece of data to set. - */ - data(element: Element, key: string): any; - /** - * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. - * - * @param element The DOM element to associate with the data. - */ - data(element: Element): any; - - /** - * Execute the next function on the queue for the matched element. - * - * @param element A DOM element from which to remove and execute a queued function. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - dequeue(element: Element, queueName?: string): void; - - /** - * Determine whether an element has any jQuery data associated with it. - * - * @param element A DOM element to be checked for data. - */ - hasData(element: Element): boolean; - - /** - * Show the queue of functions to be executed on the matched element. - * - * @param element A DOM element to inspect for an attached queue. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - queue(element: Element, queueName?: string): any[]; - /** - * Manipulate the queue of functions to be executed on the matched element. - * - * @param element A DOM element where the array of queued functions is attached. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param newQueue An array of functions to replace the current queue contents. - */ - queue(element: Element, queueName: string, newQueue: Function[]): JQuery; - /** - * Manipulate the queue of functions to be executed on the matched element. - * - * @param element A DOM element on which to add a queued function. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param callback The new function to add to the queue. - */ - queue(element: Element, queueName: string, callback: Function): JQuery; - - /** - * Remove a previously-stored piece of data. - * - * @param element A DOM element from which to remove data. - * @param name A string naming the piece of data to remove. - */ - removeData(element: Element, name?: string): JQuery; - - /** - * A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. - * - * @param beforeStart A function that is called just before the constructor returns. - */ - Deferred(beforeStart?: (deferred: JQueryDeferred) => any): JQueryDeferred; - - /** - * Effects - */ - fx: { - tick: () => void; - /** - * The rate (in milliseconds) at which animations fire. - */ - interval: number; - stop: () => void; - speeds: { slow: number; fast: number; }; - /** - * Globally disable all animations. - */ - off: boolean; - step: any; - }; - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fnction The function whose context will be changed. - * @param context The object to which the context (this) of the function should be set. - * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. - */ - proxy(fnction: (...args: any[]) => any, context: Object, ...additionalArguments: any[]): any; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param context The object to which the context (this) of the function should be set. - * @param name The name of the function whose context will be changed (should be a property of the context object). - * @param additionalArguments Any number of arguments to be passed to the function named in the name argument. - */ - proxy(context: Object, name: string, ...additionalArguments: any[]): any; - - Event: JQueryEventConstructor; - - /** - * Takes a string and throws an exception containing it. - * - * @param message The message to send out. - */ - error(message: any): JQuery; - - expr: any; - fn: any; //TODO: Decide how we want to type this - - isReady: boolean; - - // Properties - support: JQuerySupport; - - /** - * Check to see if a DOM element is a descendant of another DOM element. - * - * @param container The DOM element that may contain the other element. - * @param contained The DOM element that may be contained by (a descendant of) the other element. - */ - contains(container: Element, contained: Element): boolean; - - /** - * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. - * - * @param collection The object or array to iterate over. - * @param callback The function that will be executed on every object. - */ - each( - collection: T[], - callback: (indexInArray: number, valueOfElement: T) => any - ): any; - - /** - * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. - * - * @param collection The object or array to iterate over. - * @param callback The function that will be executed on every object. - */ - each( - collection: any, - callback: (indexInArray: any, valueOfElement: any) => any - ): any; - - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument. - * @param object1 An object containing additional properties to merge in. - * @param objectN Additional objects containing properties to merge in. - */ - extend(target: any, object1?: any, ...objectN: any[]): any; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). - * @param target The object to extend. It will receive the new properties. - * @param object1 An object containing additional properties to merge in. - * @param objectN Additional objects containing properties to merge in. - */ - extend(deep: boolean, target: any, object1?: any, ...objectN: any[]): any; - - /** - * Execute some JavaScript code globally. - * - * @param code The JavaScript code to execute. - */ - globalEval(code: string): any; - - /** - * Finds the elements of an array which satisfy a filter function. The original array is not affected. - * - * @param array The array to search through. - * @param func The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object. - * @param invert If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false. - */ - grep(array: T[], func: (elementOfArray: T, indexInArray: number) => boolean, invert?: boolean): T[]; - - /** - * Search for a specified value within an array and return its index (or -1 if not found). - * - * @param value The value to search for. - * @param array An array through which to search. - * @param fromIndex he index of the array at which to begin the search. The default is 0, which will search the whole array. - */ - inArray(value: T, array: T[], fromIndex?: number): number; - - /** - * Determine whether the argument is an array. - * - * @param obj Object to test whether or not it is an array. - */ - isArray(obj: any): boolean; - /** - * Check to see if an object is empty (contains no enumerable properties). - * - * @param obj The object that will be checked to see if it's empty. - */ - isEmptyObject(obj: any): boolean; - /** - * Determine if the argument passed is a Javascript function object. - * - * @param obj Object to test whether or not it is a function. - */ - isFunction(obj: any): boolean; - /** - * Determines whether its argument is a number. - * - * @param obj The value to be tested. - */ - isNumeric(value: any): boolean; - /** - * Check to see if an object is a plain object (created using "{}" or "new Object"). - * - * @param obj The object that will be checked to see if it's a plain object. - */ - isPlainObject(obj: any): boolean; - /** - * Determine whether the argument is a window. - * - * @param obj Object to test whether or not it is a window. - */ - isWindow(obj: any): boolean; - /** - * Check to see if a DOM node is within an XML document (or is an XML document). - * - * @param node he DOM node that will be checked to see if it's in an XML document. - */ - isXMLDoc(node: Node): boolean; - - /** - * Convert an array-like object into a true JavaScript array. - * - * @param obj Any object to turn into a native Array. - */ - makeArray(obj: any): any[]; - - /** - * Translate all items in an array or object to new array of items. - * - * @param array The Array to translate. - * @param callback The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object. - */ - map(array: T[], callback: (elementOfArray: T, indexInArray: number) => U): U[]; - /** - * Translate all items in an array or object to new array of items. - * - * @param arrayOrObject The Array or Object to translate. - * @param callback The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object. - */ - map(arrayOrObject: any, callback: (value: any, indexOrKey: any) => any): any; - - /** - * Merge the contents of two arrays together into the first array. - * - * @param first The first array to merge, the elements of second added. - * @param second The second array to merge into the first, unaltered. - */ - merge(first: T[], second: T[]): T[]; - - /** - * An empty function. - */ - noop(): any; - - /** - * Return a number representing the current time. - */ - now(): number; - - /** - * Takes a well-formed JSON string and returns the resulting JavaScript object. - * - * @param json The JSON string to parse. - */ - parseJSON(json: string): any; - - /** - * Parses a string into an XML document. - * - * @param data a well-formed XML string to be parsed - */ - parseXML(data: string): XMLDocument; - - /** - * Remove the whitespace from the beginning and end of a string. - * - * @param str Remove the whitespace from the beginning and end of a string. - */ - trim(str: string): string; - - /** - * Determine the internal JavaScript [[Class]] of an object. - * - * @param obj Object to get the internal JavaScript [[Class]] of. - */ - type(obj: any): string; - - /** - * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers. - * - * @param array The Array of DOM elements. - */ - unique(array: Element[]): Element[]; - - /** - * Parses a string into an array of DOM nodes. - * - * @param data HTML string to be parsed - * @param context DOM element to serve as the context in which the HTML fragment will be created - * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string - */ - parseHTML(data: string, context?: HTMLElement, keepScripts?: boolean): any[]; - - /** - * Parses a string into an array of DOM nodes. - * - * @param data HTML string to be parsed - * @param context DOM element to serve as the context in which the HTML fragment will be created - * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string - */ - parseHTML(data: string, context?: Document, keepScripts?: boolean): any[]; -} - -/** - * The jQuery instance members - */ -interface JQuery { - /** - * Register a handler to be called when Ajax requests complete. This is an AjaxEvent. - * - * @param handler The function to be invoked. - */ - ajaxComplete(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: any) => any): JQuery; - /** - * Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxError(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxSettings: JQueryAjaxSettings, thrownError: any) => any): JQuery; - /** - * Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxSend(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxOptions: JQueryAjaxSettings) => any): JQuery; - /** - * Register a handler to be called when the first Ajax request begins. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxStart(handler: () => any): JQuery; - /** - * Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxStop(handler: () => any): JQuery; - /** - * Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxSuccess(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: JQueryAjaxSettings) => any): JQuery; - - /** - * Load data from the server and place the returned HTML into the matched element. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param complete A callback function that is executed when the request completes. - */ - load(url: string, data?: string|Object, complete?: (responseText: string, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any): JQuery; - - /** - * Encode a set of form elements as a string for submission. - */ - serialize(): string; - /** - * Encode a set of form elements as an array of names and values. - */ - serializeArray(): JQuerySerializeArrayElement[]; - - /** - * Adds the specified class(es) to each of the set of matched elements. - * - * @param className One or more space-separated classes to be added to the class attribute of each matched element. - */ - addClass(className: string): JQuery; - /** - * Adds the specified class(es) to each of the set of matched elements. - * - * @param function A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set. - */ - addClass(func: (index: number, className: string) => string): JQuery; - - /** - * Add the previous set of elements on the stack to the current set, optionally filtered by a selector. - */ - addBack(selector?: string): JQuery; - - /** - * Get the value of an attribute for the first element in the set of matched elements. - * - * @param attributeName The name of the attribute to get. - */ - attr(attributeName: string): string; - /** - * Set one or more attributes for the set of matched elements. - * - * @param attributeName The name of the attribute to set. - * @param value A value to set for the attribute. - */ - attr(attributeName: string, value: string|number): JQuery; - /** - * Set one or more attributes for the set of matched elements. - * - * @param attributeName The name of the attribute to set. - * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments. - */ - attr(attributeName: string, func: (index: number, attr: string) => string|number): JQuery; - /** - * Set one or more attributes for the set of matched elements. - * - * @param attributes An object of attribute-value pairs to set. - */ - attr(attributes: Object): JQuery; - - /** - * Determine whether any of the matched elements are assigned the given class. - * - * @param className The class name to search for. - */ - hasClass(className: string): boolean; - - /** - * Get the HTML contents of the first element in the set of matched elements. - */ - html(): string; - /** - * Set the HTML contents of each element in the set of matched elements. - * - * @param htmlString A string of HTML to set as the content of each matched element. - */ - html(htmlString: string): JQuery; - /** - * Set the HTML contents of each element in the set of matched elements. - * - * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. - */ - html(func: (index: number, oldhtml: string) => string): JQuery; - /** - * Set the HTML contents of each element in the set of matched elements. - * - * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. - */ - - /** - * Get the value of a property for the first element in the set of matched elements. - * - * @param propertyName The name of the property to get. - */ - prop(propertyName: string): any; - /** - * Set one or more properties for the set of matched elements. - * - * @param propertyName The name of the property to set. - * @param value A value to set for the property. - */ - prop(propertyName: string, value: string|number|boolean): JQuery; - /** - * Set one or more properties for the set of matched elements. - * - * @param properties An object of property-value pairs to set. - */ - prop(properties: Object): JQuery; - /** - * Set one or more properties for the set of matched elements. - * - * @param propertyName The name of the property to set. - * @param func A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element. - */ - prop(propertyName: string, func: (index: number, oldPropertyValue: any) => any): JQuery; - - /** - * Remove an attribute from each element in the set of matched elements. - * - * @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes. - */ - removeAttr(attributeName: string): JQuery; - - /** - * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. - * - * @param className One or more space-separated classes to be removed from the class attribute of each matched element. - */ - removeClass(className?: string): JQuery; - /** - * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. - * - * @param function A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments. - */ - removeClass(func: (index: number, className: string) => string): JQuery; - - /** - * Remove a property for the set of matched elements. - * - * @param propertyName The name of the property to remove. - */ - removeProp(propertyName: string): JQuery; - - /** - * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. - * - * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. - * @param swtch A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. - */ - toggleClass(className: string, swtch?: boolean): JQuery; - /** - * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. - * - * @param swtch A boolean value to determine whether the class should be added or removed. - */ - toggleClass(swtch?: boolean): JQuery; - /** - * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. - * - * @param func A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments. - * @param swtch A boolean value to determine whether the class should be added or removed. - */ - toggleClass(func: (index: number, className: string, swtch: boolean) => string, swtch?: boolean): JQuery; - - /** - * Get the current value of the first element in the set of matched elements. - */ - val(): any; - /** - * Set the value of each element in the set of matched elements. - * - * @param value A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked. - */ - val(value: string|string[]): JQuery; - /** - * Set the value of each element in the set of matched elements. - * - * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. - */ - val(func: (index: number, value: string) => string): JQuery; - - - /** - * Get the value of style properties for the first element in the set of matched elements. - * - * @param propertyName A CSS property. - */ - css(propertyName: string): string; - /** - * Set one or more CSS properties for the set of matched elements. - * - * @param propertyName A CSS property name. - * @param value A value to set for the property. - */ - css(propertyName: string, value: string|number): JQuery; - /** - * Set one or more CSS properties for the set of matched elements. - * - * @param propertyName A CSS property name. - * @param value A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. - */ - css(propertyName: string, value: (index: number, value: string) => string|number): JQuery; - /** - * Set one or more CSS properties for the set of matched elements. - * - * @param properties An object of property-value pairs to set. - */ - css(properties: Object): JQuery; - - /** - * Get the current computed height for the first element in the set of matched elements. - */ - height(): number; - /** - * Set the CSS height of every matched element. - * - * @param value An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string). - */ - height(value: number|string): JQuery; - /** - * Set the CSS height of every matched element. - * - * @param func A function returning the height to set. Receives the index position of the element in the set and the old height as arguments. Within the function, this refers to the current element in the set. - */ - height(func: (index: number, height: number) => number|string): JQuery; - - /** - * Get the current computed height for the first element in the set of matched elements, including padding but not border. - */ - innerHeight(): number; - - /** - * Sets the inner height on elements in the set of matched elements, including padding but not border. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - innerHeight(height: number|string): JQuery; - - /** - * Get the current computed width for the first element in the set of matched elements, including padding but not border. - */ - innerWidth(): number; - - /** - * Sets the inner width on elements in the set of matched elements, including padding but not border. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - innerWidth(width: number|string): JQuery; - - /** - * Get the current coordinates of the first element in the set of matched elements, relative to the document. - */ - offset(): JQueryCoordinates; - /** - * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. - * - * @param coordinates An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. - */ - offset(coordinates: JQueryCoordinates): JQuery; - /** - * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. - * - * @param func A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new top and left properties. - */ - offset(func: (index: number, coords: JQueryCoordinates) => JQueryCoordinates): JQuery; - - /** - * Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without "px") representation of the value or null if called on an empty set of elements. - * - * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. - */ - outerHeight(includeMargin?: boolean): number; - - /** - * Sets the outer height on elements in the set of matched elements, including padding and border. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - outerHeight(height: number|string): JQuery; - - /** - * Get the current computed width for the first element in the set of matched elements, including padding and border. - * - * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. - */ - outerWidth(includeMargin?: boolean): number; - - /** - * Sets the outer width on elements in the set of matched elements, including padding and border. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - outerWidth(width: number|string): JQuery; - - /** - * Get the current coordinates of the first element in the set of matched elements, relative to the offset parent. - */ - position(): JQueryCoordinates; - - /** - * Get the current horizontal position of the scroll bar for the first element in the set of matched elements or set the horizontal position of the scroll bar for every matched element. - */ - scrollLeft(): number; - /** - * Set the current horizontal position of the scroll bar for each of the set of matched elements. - * - * @param value An integer indicating the new position to set the scroll bar to. - */ - scrollLeft(value: number): JQuery; - - /** - * Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element. - */ - scrollTop(): number; - /** - * Set the current vertical position of the scroll bar for each of the set of matched elements. - * - * @param value An integer indicating the new position to set the scroll bar to. - */ - scrollTop(value: number): JQuery; - - /** - * Get the current computed width for the first element in the set of matched elements. - */ - width(): number; - /** - * Set the CSS width of each element in the set of matched elements. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - width(value: number|string): JQuery; - /** - * Set the CSS width of each element in the set of matched elements. - * - * @param func A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set. - */ - width(func: (index: number, width: number) => number|string): JQuery; - - /** - * Remove from the queue all items that have not yet been run. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - clearQueue(queueName?: string): JQuery; - - /** - * Store arbitrary data associated with the matched elements. - * - * @param key A string naming the piece of data to set. - * @param value The new data value; it can be any Javascript type including Array or Object. - */ - data(key: string, value: any): JQuery; - /** - * Store arbitrary data associated with the matched elements. - * - * @param obj An object of key-value pairs of data to update. - */ - data(obj: { [key: string]: any; }): JQuery; - /** - * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. - * - * @param key Name of the data stored. - */ - data(key: string): any; - /** - * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. - */ - data(): any; - - /** - * Execute the next function on the queue for the matched elements. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - dequeue(queueName?: string): JQuery; - - /** - * Remove a previously-stored piece of data. - * - * @param name A string naming the piece of data to delete or space-separated string naming the pieces of data to delete. - */ - removeData(name: string): JQuery; - /** - * Remove a previously-stored piece of data. - * - * @param list An array of strings naming the pieces of data to delete. - */ - removeData(list: string[]): JQuery; - - /** - * Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. - * - * @param type The type of queue that needs to be observed. (default: fx) - * @param target Object onto which the promise methods have to be attached - */ - promise(type?: string, target?: Object): JQueryPromise; - - /** - * Perform a custom animation of a set of CSS properties. - * - * @param properties An object of CSS properties and values that the animation will move toward. - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - animate(properties: Object, duration?: string|number, complete?: Function): JQuery; - /** - * Perform a custom animation of a set of CSS properties. - * - * @param properties An object of CSS properties and values that the animation will move toward. - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. (default: swing) - * @param complete A function to call once the animation is complete. - */ - animate(properties: Object, duration?: string|number, easing?: string, complete?: Function): JQuery; - /** - * Perform a custom animation of a set of CSS properties. - * - * @param properties An object of CSS properties and values that the animation will move toward. - * @param options A map of additional options to pass to the method. - */ - animate(properties: Object, options: JQueryAnimationOptions): JQuery; - - /** - * Set a timer to delay execution of subsequent items in the queue. - * - * @param duration An integer indicating the number of milliseconds to delay execution of the next item in the queue. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - delay(duration: number, queueName?: string): JQuery; - - /** - * Display the matched elements by fading them to opaque. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - fadeIn(duration?: number|string, complete?: Function): JQuery; - /** - * Display the matched elements by fading them to opaque. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - fadeIn(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display the matched elements by fading them to opaque. - * - * @param options A map of additional options to pass to the method. - */ - fadeIn(options: JQueryAnimationOptions): JQuery; - - /** - * Hide the matched elements by fading them to transparent. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - fadeOut(duration?: number|string, complete?: Function): JQuery; - /** - * Hide the matched elements by fading them to transparent. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - fadeOut(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Hide the matched elements by fading them to transparent. - * - * @param options A map of additional options to pass to the method. - */ - fadeOut(options: JQueryAnimationOptions): JQuery; - - /** - * Adjust the opacity of the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param opacity A number between 0 and 1 denoting the target opacity. - * @param complete A function to call once the animation is complete. - */ - fadeTo(duration: string|number, opacity: number, complete?: Function): JQuery; - /** - * Adjust the opacity of the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param opacity A number between 0 and 1 denoting the target opacity. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - fadeTo(duration: string|number, opacity: number, easing?: string, complete?: Function): JQuery; - - /** - * Display or hide the matched elements by animating their opacity. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - fadeToggle(duration?: number|string, complete?: Function): JQuery; - /** - * Display or hide the matched elements by animating their opacity. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - fadeToggle(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display or hide the matched elements by animating their opacity. - * - * @param options A map of additional options to pass to the method. - */ - fadeToggle(options: JQueryAnimationOptions): JQuery; - - /** - * Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements. - * - * @param queue The name of the queue in which to stop animations. - */ - finish(queue?: string): JQuery; - - /** - * Hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - hide(duration?: number|string, complete?: Function): JQuery; - /** - * Hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - hide(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Hide the matched elements. - * - * @param options A map of additional options to pass to the method. - */ - hide(options: JQueryAnimationOptions): JQuery; - - /** - * Display the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - show(duration?: number|string, complete?: Function): JQuery; - /** - * Display the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - show(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display the matched elements. - * - * @param options A map of additional options to pass to the method. - */ - show(options: JQueryAnimationOptions): JQuery; - - /** - * Display the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - slideDown(duration?: number|string, complete?: Function): JQuery; - /** - * Display the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - slideDown(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display the matched elements with a sliding motion. - * - * @param options A map of additional options to pass to the method. - */ - slideDown(options: JQueryAnimationOptions): JQuery; - - /** - * Display or hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - slideToggle(duration?: number|string, complete?: Function): JQuery; - /** - * Display or hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - slideToggle(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display or hide the matched elements with a sliding motion. - * - * @param options A map of additional options to pass to the method. - */ - slideToggle(options: JQueryAnimationOptions): JQuery; - - /** - * Hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - slideUp(duration?: number|string, complete?: Function): JQuery; - /** - * Hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - slideUp(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Hide the matched elements with a sliding motion. - * - * @param options A map of additional options to pass to the method. - */ - slideUp(options: JQueryAnimationOptions): JQuery; - - /** - * Stop the currently-running animation on the matched elements. - * - * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. - * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. - */ - stop(clearQueue?: boolean, jumpToEnd?: boolean): JQuery; - /** - * Stop the currently-running animation on the matched elements. - * - * @param queue The name of the queue in which to stop animations. - * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. - * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. - */ - stop(queue?: string, clearQueue?: boolean, jumpToEnd?: boolean): JQuery; - - /** - * Display or hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - toggle(duration?: number|string, complete?: Function): JQuery; - /** - * Display or hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - toggle(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display or hide the matched elements. - * - * @param options A map of additional options to pass to the method. - */ - toggle(options: JQueryAnimationOptions): JQuery; - /** - * Display or hide the matched elements. - * - * @param showOrHide A Boolean indicating whether to show or hide the elements. - */ - toggle(showOrHide: boolean): JQuery; - - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - bind(eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param handler A function to execute each time the event is triggered. - */ - bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param eventData An object containing data that will be passed to the event handler. - * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. - */ - bind(eventType: string, eventData: any, preventBubble: boolean): JQuery; - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. - */ - bind(eventType: string, preventBubble: boolean): JQuery; - /** - * Attach a handler to an event for the elements. - * - * @param events An object containing one or more DOM event types and functions to execute for them. - */ - bind(events: any): JQuery; - - /** - * Trigger the "blur" event on an element - */ - blur(): JQuery; - /** - * Bind an event handler to the "blur" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - blur(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "blur" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - blur(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "change" event on an element. - */ - change(): JQuery; - /** - * Bind an event handler to the "change" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - change(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "change" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - change(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "click" event on an element. - */ - click(): JQuery; - /** - * Bind an event handler to the "click" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - */ - click(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "click" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "dblclick" event on an element. - */ - dblclick(): JQuery; - /** - * Bind an event handler to the "dblclick" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - dblclick(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "dblclick" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - dblclick(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - delegate(selector: any, eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - delegate(selector: any, eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "focus" event on an element. - */ - focus(): JQuery; - /** - * Bind an event handler to the "focus" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - focus(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "focus" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - focus(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Bind an event handler to the "focusin" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - focusin(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "focusin" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - focusin(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Bind an event handler to the "focusout" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - focusout(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "focusout" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - focusout(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. - * - * @param handlerIn A function to execute when the mouse pointer enters the element. - * @param handlerOut A function to execute when the mouse pointer leaves the element. - */ - hover(handlerIn: (eventObject: JQueryEventObject) => any, handlerOut: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. - * - * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. - */ - hover(handlerInOut: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "keydown" event on an element. - */ - keydown(): JQuery; - /** - * Bind an event handler to the "keydown" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - keydown(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; - /** - * Bind an event handler to the "keydown" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - keydown(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; - - /** - * Trigger the "keypress" event on an element. - */ - keypress(): JQuery; - /** - * Bind an event handler to the "keypress" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - keypress(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; - /** - * Bind an event handler to the "keypress" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - keypress(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; - - /** - * Trigger the "keyup" event on an element. - */ - keyup(): JQuery; - /** - * Bind an event handler to the "keyup" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - keyup(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; - /** - * Bind an event handler to the "keyup" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - keyup(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; - - /** - * Bind an event handler to the "load" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - load(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "load" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - load(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "mousedown" event on an element. - */ - mousedown(): JQuery; - /** - * Bind an event handler to the "mousedown" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mousedown(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to the "mousedown" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mousedown(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mouseenter" event on an element. - */ - mouseenter(): JQuery; - /** - * Bind an event handler to be fired when the mouse enters an element. - * - * @param handler A function to execute when the event is triggered. - */ - mouseenter(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to be fired when the mouse enters an element. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseenter(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mouseleave" event on an element. - */ - mouseleave(): JQuery; - /** - * Bind an event handler to be fired when the mouse leaves an element. - * - * @param handler A function to execute when the event is triggered. - */ - mouseleave(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to be fired when the mouse leaves an element. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseleave(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mousemove" event on an element. - */ - mousemove(): JQuery; - /** - * Bind an event handler to the "mousemove" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mousemove(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to the "mousemove" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mousemove(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mouseout" event on an element. - */ - mouseout(): JQuery; - /** - * Bind an event handler to the "mouseout" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mouseout(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to the "mouseout" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseout(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mouseover" event on an element. - */ - mouseover(): JQuery; - /** - * Bind an event handler to the "mouseover" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mouseover(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to the "mouseover" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseover(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mouseup" event on an element. - */ - mouseup(): JQuery; - /** - * Bind an event handler to the "mouseup" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mouseup(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to the "mouseup" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseup(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Remove an event handler. - */ - off(): JQuery; - /** - * Remove an event handler. - * - * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". - * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: string, selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Remove an event handler. - * - * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Remove an event handler. - * - * @param events An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s). - * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. - */ - off(events: { [key: string]: any; }, selector?: string): JQuery; - - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: string, data : any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: string, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). - * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event occurs. - */ - on(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). - * @param data Data to be passed to the handler in event.data when an event occurs. - */ - on(events: { [key: string]: any; }, data?: any): JQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. - * @param handler A function to execute at the time the event is triggered. - */ - one(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. - * @param data An object containing data that will be passed to the event handler. - * @param handler A function to execute at the time the event is triggered. - */ - one(events: string, data: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - one(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - one(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). - * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event occurs. - */ - one(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). - * @param data Data to be passed to the handler in event.data when an event occurs. - */ - one(events: { [key: string]: any; }, data?: any): JQuery; - - - /** - * Specify a function to execute when the DOM is fully loaded. - * - * @param handler A function to execute after the DOM is ready. - */ - ready(handler: (jQueryAlias?: JQueryStatic) => any): JQuery; - - /** - * Trigger the "resize" event on an element. - */ - resize(): JQuery; - /** - * Bind an event handler to the "resize" JavaScript event. - * - * @param handler A function to execute each time the event is triggered. - */ - resize(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "resize" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - resize(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "scroll" event on an element. - */ - scroll(): JQuery; - /** - * Bind an event handler to the "scroll" JavaScript event. - * - * @param handler A function to execute each time the event is triggered. - */ - scroll(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "scroll" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - scroll(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "select" event on an element. - */ - select(): JQuery; - /** - * Bind an event handler to the "select" JavaScript event. - * - * @param handler A function to execute each time the event is triggered. - */ - select(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "select" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - select(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "submit" event on an element. - */ - submit(): JQuery; - /** - * Bind an event handler to the "submit" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - submit(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "submit" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - submit(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Execute all handlers and behaviors attached to the matched elements for the given event type. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param extraParameters Additional parameters to pass along to the event handler. - */ - trigger(eventType: string, extraParameters?: any[]|Object): JQuery; - /** - * Execute all handlers and behaviors attached to the matched elements for the given event type. - * - * @param event A jQuery.Event object. - * @param extraParameters Additional parameters to pass along to the event handler. - */ - trigger(event: JQueryEventObject, extraParameters?: any[]|Object): JQuery; - - /** - * Execute all handlers attached to an element for an event. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param extraParameters An array of additional parameters to pass along to the event handler. - */ - triggerHandler(eventType: string, ...extraParameters: any[]): Object; - - /** - * Remove a previously-attached event handler from the elements. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param handler The function that is to be no longer executed. - */ - unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Remove a previously-attached event handler from the elements. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). - */ - unbind(eventType: string, fls: boolean): JQuery; - /** - * Remove a previously-attached event handler from the elements. - * - * @param evt A JavaScript event object as passed to an event handler. - */ - unbind(evt: any): JQuery; - - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - */ - undelegate(): JQuery; - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * - * @param selector A selector which will be used to filter the event results. - * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" - * @param handler A function to execute at the time the event is triggered. - */ - undelegate(selector: string, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * - * @param selector A selector which will be used to filter the event results. - * @param events An object of one or more event types and previously bound functions to unbind from them. - */ - undelegate(selector: string, events: Object): JQuery; - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * - * @param namespace A string containing a namespace to unbind all events from. - */ - undelegate(namespace: string): JQuery; - - /** - * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) - * - * @param handler A function to execute when the event is triggered. - */ - unload(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) - * - * @param eventData A plain object of data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - unload(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document. (DEPRECATED from v1.10) - */ - context: Element; - - jquery: string; - - /** - * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) - * - * @param handler A function to execute when the event is triggered. - */ - error(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) - * - * @param eventData A plain object of data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - error(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Add a collection of DOM elements onto the jQuery stack. - * - * @param elements An array of elements to push onto the stack and make into a new jQuery object. - */ - pushStack(elements: any[]): JQuery; - /** - * Add a collection of DOM elements onto the jQuery stack. - * - * @param elements An array of elements to push onto the stack and make into a new jQuery object. - * @param name The name of a jQuery method that generated the array of elements. - * @param arguments The arguments that were passed in to the jQuery method (for serialization). - */ - pushStack(elements: any[], name: string, arguments: any[]): JQuery; - - /** - * Insert content, specified by the parameter, after each element in the set of matched elements. - * - * param content1 HTML string, DOM element, array of elements, or jQuery object to insert after each element in the set of matched elements. - * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. - */ - after(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; - /** - * Insert content, specified by the parameter, after each element in the set of matched elements. - * - * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. - */ - after(func: (index: number, html: string) => string|Element|JQuery): JQuery; - - /** - * Insert content, specified by the parameter, to the end of each element in the set of matched elements. - * - * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. - * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. - */ - append(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; - /** - * Insert content, specified by the parameter, to the end of each element in the set of matched elements. - * - * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. - */ - append(func: (index: number, html: string) => string|Element|JQuery): JQuery; - - /** - * Insert every element in the set of matched elements to the end of the target. - * - * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. - */ - appendTo(target: JQuery|any[]|Element|string): JQuery; - - /** - * Insert content, specified by the parameter, before each element in the set of matched elements. - * - * param content1 HTML string, DOM element, array of elements, or jQuery object to insert before each element in the set of matched elements. - * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. - */ - before(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; - /** - * Insert content, specified by the parameter, before each element in the set of matched elements. - * - * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. - */ - before(func: (index: number, html: string) => string|Element|JQuery): JQuery; - - /** - * Create a deep copy of the set of matched elements. - * - * param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. - * param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false). - */ - clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): JQuery; - - /** - * Remove the set of matched elements from the DOM. - * - * param selector A selector expression that filters the set of matched elements to be removed. - */ - detach(selector?: string): JQuery; - - /** - * Remove all child nodes of the set of matched elements from the DOM. - */ - empty(): JQuery; - - /** - * Insert every element in the set of matched elements after the target. - * - * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. - */ - insertAfter(target: JQuery|any[]|Element|Text|string): JQuery; - - /** - * Insert every element in the set of matched elements before the target. - * - * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. - */ - insertBefore(target: JQuery|any[]|Element|Text|string): JQuery; - - /** - * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. - * - * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. - * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. - */ - prepend(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; - /** - * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. - * - * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. - */ - prepend(func: (index: number, html: string) => string|Element|JQuery): JQuery; - - /** - * Insert every element in the set of matched elements to the beginning of the target. - * - * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. - */ - prependTo(target: JQuery|any[]|Element|string): JQuery; - - /** - * Remove the set of matched elements from the DOM. - * - * @param selector A selector expression that filters the set of matched elements to be removed. - */ - remove(selector?: string): JQuery; - - /** - * Replace each target element with the set of matched elements. - * - * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. - */ - replaceAll(target: JQuery|any[]|Element|string): JQuery; - - /** - * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. - * - * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. - */ - replaceWith(newContent: JQuery|any[]|Element|Text|string): JQuery; - /** - * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. - * - * param func A function that returns content with which to replace the set of matched elements. - */ - replaceWith(func: () => Element|JQuery): JQuery; - - /** - * Get the combined text contents of each element in the set of matched elements, including their descendants. - */ - text(): string; - /** - * Set the content of each element in the set of matched elements to the specified text. - * - * @param text The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation. - */ - text(text: string|number|boolean): JQuery; - /** - * Set the content of each element in the set of matched elements to the specified text. - * - * @param func A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments. - */ - text(func: (index: number, text: string) => string): JQuery; - - /** - * Retrieve all the elements contained in the jQuery set, as an array. - */ - toArray(): any[]; - - /** - * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. - */ - unwrap(): JQuery; - - /** - * Wrap an HTML structure around each element in the set of matched elements. - * - * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. - */ - wrap(wrappingElement: JQuery|Element|string): JQuery; - /** - * Wrap an HTML structure around each element in the set of matched elements. - * - * @param func A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. - */ - wrap(func: (index: number) => string|JQuery): JQuery; - - /** - * Wrap an HTML structure around all elements in the set of matched elements. - * - * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. - */ - wrapAll(wrappingElement: JQuery|Element|string): JQuery; - wrapAll(func: (index: number) => string): JQuery; - - /** - * Wrap an HTML structure around the content of each element in the set of matched elements. - * - * @param wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements. - */ - wrapInner(wrappingElement: JQuery|Element|string): JQuery; - /** - * Wrap an HTML structure around the content of each element in the set of matched elements. - * - * @param func A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. - */ - wrapInner(func: (index: number) => string): JQuery; - - /** - * Iterate over a jQuery object, executing a function for each matched element. - * - * @param func A function to execute for each matched element. - */ - each(func: (index: number, elem: Element) => any): JQuery; - - /** - * Retrieve one of the elements matched by the jQuery object. - * - * @param index A zero-based integer indicating which element to retrieve. - */ - get(index: number): HTMLElement; - /** - * Retrieve the elements matched by the jQuery object. - */ - get(): any[]; - - /** - * Search for a given element from among the matched elements. - */ - index(): number; - /** - * Search for a given element from among the matched elements. - * - * @param selector A selector representing a jQuery collection in which to look for an element. - */ - index(selector: string|JQuery|Element): number; - - /** - * The number of elements in the jQuery object. - */ - length: number; - /** - * A selector representing selector passed to jQuery(), if any, when creating the original set. - * version deprecated: 1.7, removed: 1.9 - */ - selector: string; - [index: string]: any; - [index: number]: HTMLElement; - - /** - * Add elements to the set of matched elements. - * - * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements. - * @param context The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method. - */ - add(selector: string, context?: Element): JQuery; - /** - * Add elements to the set of matched elements. - * - * @param elements One or more elements to add to the set of matched elements. - */ - add(...elements: Element[]): JQuery; - /** - * Add elements to the set of matched elements. - * - * @param html An HTML fragment to add to the set of matched elements. - */ - add(html: string): JQuery; - /** - * Add elements to the set of matched elements. - * - * @param obj An existing jQuery object to add to the set of matched elements. - */ - add(obj: JQuery): JQuery; - - /** - * Get the children of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - children(selector?: string): JQuery; - - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * - * @param selector A string containing a selector expression to match elements against. - */ - closest(selector: string): JQuery; - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * - * @param selector A string containing a selector expression to match elements against. - * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. - */ - closest(selector: string, context?: Element): JQuery; - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * - * @param obj A jQuery object to match elements against. - */ - closest(obj: JQuery): JQuery; - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * - * @param element An element to match elements against. - */ - closest(element: Element): JQuery; - - /** - * Get an array of all the elements and selectors matched against the current element up through the DOM tree. - * - * @param selectors An array or string containing a selector expression to match elements against (can also be a jQuery object). - * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. - */ - closest(selectors: any, context?: Element): any[]; - - /** - * Get the children of each element in the set of matched elements, including text and comment nodes. - */ - contents(): JQuery; - - /** - * End the most recent filtering operation in the current chain and return the set of matched elements to its previous state. - */ - end(): JQuery; - - /** - * Reduce the set of matched elements to the one at the specified index. - * - * @param index An integer indicating the 0-based position of the element. OR An integer indicating the position of the element, counting backwards from the last element in the set. - * - */ - eq(index: number): JQuery; - - /** - * Reduce the set of matched elements to those that match the selector or pass the function's test. - * - * @param selector A string containing a selector expression to match the current set of elements against. - */ - filter(selector: string): JQuery; - /** - * Reduce the set of matched elements to those that match the selector or pass the function's test. - * - * @param func A function used as a test for each element in the set. this is the current DOM element. - */ - filter(func: (index: number, element: Element) => any): JQuery; - /** - * Reduce the set of matched elements to those that match the selector or pass the function's test. - * - * @param element An element to match the current set of elements against. - */ - filter(element: Element): JQuery; - /** - * Reduce the set of matched elements to those that match the selector or pass the function's test. - * - * @param obj An existing jQuery object to match the current set of elements against. - */ - filter(obj: JQuery): JQuery; - - /** - * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * - * @param selector A string containing a selector expression to match elements against. - */ - find(selector: string): JQuery; - /** - * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * - * @param element An element to match elements against. - */ - find(element: Element): JQuery; - /** - * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * - * @param obj A jQuery object to match elements against. - */ - find(obj: JQuery): JQuery; - - /** - * Reduce the set of matched elements to the first in the set. - */ - first(): JQuery; - - /** - * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - * - * @param selector A string containing a selector expression to match elements against. - */ - has(selector: string): JQuery; - /** - * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - * - * @param contained A DOM element to match elements against. - */ - has(contained: Element): JQuery; - - /** - * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * - * @param selector A string containing a selector expression to match elements against. - */ - is(selector: string): boolean; - /** - * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * - * @param func A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element. - */ - is(func: (index: number, element: Element) => boolean): boolean; - /** - * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * - * @param obj An existing jQuery object to match the current set of elements against. - */ - is(obj: JQuery): boolean; - /** - * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * - * @param elements One or more elements to match the current set of elements against. - */ - is(elements: any): boolean; - - /** - * Reduce the set of matched elements to the final one in the set. - */ - last(): JQuery; - - /** - * Pass each element in the current matched set through a function, producing a new jQuery object containing the return values. - * - * @param callback A function object that will be invoked for each element in the current set. - */ - map(callback: (index: number, domElement: Element) => any): JQuery; - - /** - * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - next(selector?: string): JQuery; - - /** - * Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - nextAll(selector?: string): JQuery; - - /** - * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * - * @param selector A string containing a selector expression to indicate where to stop matching following sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - nextUntil(selector?: string, filter?: string): JQuery; - /** - * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * - * @param element A DOM node or jQuery object indicating where to stop matching following sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - nextUntil(element?: Element, filter?: string): JQuery; - /** - * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * - * @param obj A DOM node or jQuery object indicating where to stop matching following sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - nextUntil(obj?: JQuery, filter?: string): JQuery; - - /** - * Remove elements from the set of matched elements. - * - * @param selector A string containing a selector expression to match elements against. - */ - not(selector: string): JQuery; - /** - * Remove elements from the set of matched elements. - * - * @param func A function used as a test for each element in the set. this is the current DOM element. - */ - not(func: (index: number, element: Element) => boolean): JQuery; - /** - * Remove elements from the set of matched elements. - * - * @param elements One or more DOM elements to remove from the matched set. - */ - not(...elements: Element[]): JQuery; - /** - * Remove elements from the set of matched elements. - * - * @param obj An existing jQuery object to match the current set of elements against. - */ - not(obj: JQuery): JQuery; - - /** - * Get the closest ancestor element that is positioned. - */ - offsetParent(): JQuery; - - /** - * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - parent(selector?: string): JQuery; - - /** - * Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - parents(selector?: string): JQuery; - - /** - * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param selector A string containing a selector expression to indicate where to stop matching ancestor elements. - * @param filter A string containing a selector expression to match elements against. - */ - parentsUntil(selector?: string, filter?: string): JQuery; - /** - * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param element A DOM node or jQuery object indicating where to stop matching ancestor elements. - * @param filter A string containing a selector expression to match elements against. - */ - parentsUntil(element?: Element, filter?: string): JQuery; - /** - * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param obj A DOM node or jQuery object indicating where to stop matching ancestor elements. - * @param filter A string containing a selector expression to match elements against. - */ - parentsUntil(obj?: JQuery, filter?: string): JQuery; - - /** - * Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - prev(selector?: string): JQuery; - - /** - * Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - prevAll(selector?: string): JQuery; - - /** - * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param selector A string containing a selector expression to indicate where to stop matching preceding sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - prevUntil(selector?: string, filter?: string): JQuery; - /** - * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param element A DOM node or jQuery object indicating where to stop matching preceding sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - prevUntil(element?: Element, filter?: string): JQuery; - /** - * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param obj A DOM node or jQuery object indicating where to stop matching preceding sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - prevUntil(obj?: JQuery, filter?: string): JQuery; - - /** - * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - siblings(selector?: string): JQuery; - - /** - * Reduce the set of matched elements to a subset specified by a range of indices. - * - * @param start An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set. - * @param end An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set. - */ - slice(start: number, end?: number): JQuery; - - /** - * Show the queue of functions to be executed on the matched elements. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - queue(queueName?: string): any[]; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param newQueue An array of functions to replace the current queue contents. - */ - queue(newQueue: Function[]): JQuery; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. - */ - queue(callback: Function): JQuery; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param newQueue An array of functions to replace the current queue contents. - */ - queue(queueName: string, newQueue: Function[]): JQuery; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. - */ - queue(queueName: string, callback: Function): JQuery; -} -declare module "jquery" { - export = $; -} -declare var jQuery: JQueryStatic; -declare var $: JQueryStatic; diff --git a/catalog-ui/src/typings/jsMd5/md5.d.ts b/catalog-ui/src/typings/jsMd5/md5.d.ts index 3f06a6f509..475dc29a31 100644 --- a/catalog-ui/src/typings/jsMd5/md5.d.ts +++ b/catalog-ui/src/typings/jsMd5/md5.d.ts @@ -22,7 +22,7 @@ // Definitions by: Roland Greim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ -/// +/// interface JQuery { md5(value: string): string; diff --git a/catalog-ui/src/typings/tsd.d.ts b/catalog-ui/src/typings/tsd.d.ts index 4fe638ef72..fe040fc6be 100644 --- a/catalog-ui/src/typings/tsd.d.ts +++ b/catalog-ui/src/typings/tsd.d.ts @@ -18,4 +18,3 @@ * ============LICENSE_END========================================================= */ /// -/// diff --git a/catalog-ui/tslint.json b/catalog-ui/tslint.json index 86bc1841f3..1aebca880c 100644 --- a/catalog-ui/tslint.json +++ b/catalog-ui/tslint.json @@ -1,8 +1,10 @@ { - "rulesDirectory": [ - "node_modules/codelyzer" + "extends": [ + "tslint:recommended" ], "rules": { + "cognitive-complexity": false, + "trailing-comma": true, "callable-types": true, "class-name": true, "comment-format": [ @@ -12,23 +14,24 @@ "curly": true, "eofline": true, "forin": true, - "import-blacklist": [true, "rxjs"], "import-spacing": true, "indent": [ true, "spaces" ], - "interface-over-type-literal": true, - "label-position": true, + //"interface-over-type-literal": true, + //"label-position": true, + "interface-name": [true, "never-prefix"], "max-line-length": [ true, - 140 + 200 ], "member-access": false, "member-ordering": [ true, - "static-before-instance", - "variables-before-functions" + { + "order": "fields-first" + } ], "no-arg": true, "no-bitwise": true, @@ -42,18 +45,19 @@ ], "no-construct": true, "no-debugger": true, - "no-duplicate-variable": true, - "no-empty": false, + "no-empty": true, "no-empty-interface": true, "no-eval": true, - "no-inferrable-types": true, + "no-inferrable-types": false, "no-shadowed-variable": true, - "no-string-literal": false, + "no-string-literal": true, "no-string-throw": true, "no-switch-case-fall-through": true, "no-trailing-whitespace": true, - "no-unused-expression": true, - "no-use-before-declare": true, + "no-unused-expression": [ + true, + "allow-fast-null-checks" + ], "no-var-keyword": true, "object-literal-sort-keys": false, "one-line": [ @@ -68,13 +72,14 @@ true, "single" ], - "radix": true, "semicolon": [ + true, "always" ], "triple-equals": [ true, - "allow-null-check" + "allow-null-check", + "allow-undefined-check" ], "typedef-whitespace": [ true, @@ -86,31 +91,43 @@ "variable-declaration": "nospace" } ], - "typeof-compare": true, - "unified-signatures": true, - "variable-name": false, + "variable-name": [ + true, + "check-format", + "ban-keywords" + ], "whitespace": [ true, "check-branch", "check-decl", "check-operator", + "check-module", "check-separator", - "check-type" + "check-type", + "check-preblock" ], - - "directive-selector": [true, "attribute", "app", "camelCase"], - "component-selector": [true, "element", "app", "kebab-case"], - "use-input-property-decorator": true, - "use-output-property-decorator": true, - "use-host-property-decorator": true, - "no-input-rename": true, - "no-output-rename": true, - "use-life-cycle-interface": true, - "use-pipe-transform-interface": true, - "component-class-suffix": true, - "directive-class-suffix": true, - "no-access-missing-member": true, - "templates-use-public": true, - "invoke-injectable": true + "ban-types": [ + true, + [ + "Object", + "Avoid using the `Object` type. Did you mean `object`?" + ], + [ + "Boolean", + "Avoid using the `Boolean` type. Did you mean `boolean`?" + ], + [ + "Number", + "Avoid using the `Number` type. Did you mean `number`?" + ], + [ + "String", + "Avoid using the `String` type. Did you mean `string`?" + ], + [ + "Symbol", + "Avoid using the `Symbol` type. Did you mean `symbol`?" + ] + ] } -} +} \ No newline at end of file diff --git a/catalog-ui/webpack.common.js b/catalog-ui/webpack.common.js index 4482d0e014..5b745c9b05 100644 --- a/catalog-ui/webpack.common.js +++ b/catalog-ui/webpack.common.js @@ -80,7 +80,7 @@ module.exports = function(params) { enforce: "pre", test: /\.js$/, loader: "source-map-loader", - exclude: [ /\/node_modules\// ] + exclude: [ path.join(__dirname, 'node_modules') ] }, { test: /\.json$/, loader: "json-loader" }, { test: /\.html$/, loader: "html-loader" }, @@ -226,6 +226,7 @@ module.exports = function(params) { // }), new GlobCopyWebpackPlugin({ patterns: [ + "assets/preloading.css", "assets/languages", "assets/styles/fonts", "assets/styles/images", @@ -292,7 +293,7 @@ module.exports = function(params) { }), new AotPlugin({ mainPath: "main.ts", - exclude: [], + exclude: [ "**/*.spec.ts" ], tsConfigPath: "src/tsconfig.json", skipCodeGeneration: true }) diff --git a/catalog-ui/webpack.production.js b/catalog-ui/webpack.production.js index a593e37119..bb6f8efaa1 100644 --- a/catalog-ui/webpack.production.js +++ b/catalog-ui/webpack.production.js @@ -8,6 +8,7 @@ const webpackCommonConfig = require('./webpack.common'); const {GlobCopyWebpackPlugin, BaseHrefWebpackPlugin} = require('@angular/cli/plugins/webpack'); const CopyWebpackPlugin = require('copy-webpack-plugin'); var CompressionPlugin = require('compression-webpack-plugin'); +const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); var currentTime = new Date().getTime(); const params = {}; @@ -43,18 +44,7 @@ const webpackProdConfig = { } } ]), - new webpack.optimize.UglifyJsPlugin({ - beautify: false, - mangle: { - screw_ie8: true, - keep_fnames: true - }, - compress: { - warnings: false, - screw_ie8: true - }, - comments: false - }), + new UglifyJSPlugin({}), new webpack.optimize.AggressiveMergingPlugin(),//Merge chunks new CompressionPlugin({ asset: "[path]gz", diff --git a/catalog-ui/webpack.server.js b/catalog-ui/webpack.server.js index b8821cd9d1..1993617197 100644 --- a/catalog-ui/webpack.server.js +++ b/catalog-ui/webpack.server.js @@ -3,8 +3,9 @@ let path = require('path'); const mockApis = require('./configurations/mock.json').sdcConfig; const proxy = require('http-proxy-middleware'); const devPort = 9000; -const fePort = 8181; -const localhost = "localhost"; +const fePort = 8287; +const loclahost = "localhost"; // "localhost" +const portalCookieValue = "randomValue"; //for dev solely, in production - the webseal would add the cookie byitself. module.exports = function(env) { @@ -25,79 +26,66 @@ module.exports = function(env) { exclude: ['node_modules'] }, setup: server => { - let userType = mockApis.userTypes[env.role]; + let userType = mockApis.userTypes[env.role]; - let middlewares = [ - (req, res, next) => { - res.cookie(mockApis.cookie.userIdSuffix, req.headers[mockApis.cookie.userIdSuffix] || userType.userId); - res.cookie(mockApis.cookie.userEmail, req.headers[mockApis.cookie.userEmail] || userType.email); - res.cookie(mockApis.cookie.userFirstName, req.headers[mockApis.cookie.userFirstName] || userType.firstName); - res.cookie(mockApis.cookie.userLastName, req.headers[mockApis.cookie.userLastName] || userType.lastName); - next(); - } - ]; - - // Redirect all '/sdc1/feProxy/rest' to feHost - middlewares.push( - proxy(['/sdc1/feProxy/rest'], { - target: 'http://' + localhost + ':' + fePort, - changeOrigin: true, - secure: false - })); + let middlewares = [ + (req, res, next) => { + res.cookie(mockApis.cookie.userIdSuffix, req.headers[mockApis.cookie.userIdSuffix] || userType.userId); + res.cookie(mockApis.cookie.userEmail, req.headers[mockApis.cookie.userEmail] || userType.email); + res.cookie(mockApis.cookie.userFirstName, req.headers[mockApis.cookie.userFirstName] || userType.firstName); + res.cookie(mockApis.cookie.userLastName, req.headers[mockApis.cookie.userLastName] || userType.lastName); + res.cookie(mockApis.cookie.portalCookie, portalCookieValue); + next(); +} +]; - // Redirect all '/sdc1/rest' to feHost - middlewares.push( - proxy(['/sdc1/rest'],{ - target: 'http://' + localhost + ':' + fePort, - changeOrigin: true, - secure: false - })); + // Redirect all '/sdc1/feProxy/rest' to feHost + middlewares.push( + proxy(['/sdc1/feProxy/rest', '/sdc1/feProxy/uicache'],{ + target: 'http://' + loclahost + ':' + fePort, + changeOrigin: true, + secure: false + })); - // Redirect dcae urls to feHost - middlewares.push( - proxy(['/dcae','/sdc1/feProxy/dcae-api'], { - target: 'http://' + localhost + ':' + fePort, - changeOrigin: true, - secure: false, - onProxyRes: (proxyRes, req, res) => { - let setCookie = proxyRes.headers['set-cookie']; - if (setCookie) { - setCookie[0] = setCookie[0].replace(/\bSecure\b(; )?/, ''); - } - } - })); + // Redirect all '/sdc1/rest' to feHost + middlewares.push( + proxy(['/sdc1/rest'],{ + target: 'http://' + loclahost + ':' + fePort, + changeOrigin: true, + secure: false + })); - // Redirect onboarding urls to feHost - middlewares.push( - proxy(['/onboarding', '/sdc1/feProxy/onboarding-api'], { - target: 'http://' + localhost + ':' + fePort, - changeOrigin: true, - secure: false, - onProxyRes: (proxyRes, req, res) => { - let setCookie = proxyRes.headers['set-cookie']; - if (setCookie) { - setCookie[0] = setCookie[0].replace(/\bSecure\b(; )?/, ''); - } - } - })); + // Redirect dcae urls to feHost + middlewares.push( + proxy(['/dcae','/sdc1/feProxy/dcae-api'],{ + target: 'http://' + loclahost + ':' + fePort, + changeOrigin: true, + secure: false, + onProxyRes: (proxyRes, req, res) => { + let setCookie = proxyRes.headers['set-cookie']; + if (setCookie) { + setCookie[0] = setCookie[0].replace(/\bSecure\b(; )?/, ''); + } +} +})); - // Redirect workflow urls to feHost - middlewares.push( - proxy(['/sdc1/feProxy/wf', '/wf'], { - target: 'http://' + localhost + ':' + fePort, - changeOrigin: true, - secure: false, - onProxyRes: (proxyRes, req, res) => { - let setCookie = proxyRes.headers['set-cookie']; - if (setCookie) { - setCookie[0] = setCookie[0].replace(/\bSecure\b(; )?/, ''); - } - } - })); + // Redirect onboarding urls to feHost + middlewares.push( + proxy(['/onboarding','/sdc1/feProxy/onboarding-api'],{ + target: 'http://' + loclahost + ':' + fePort, + changeOrigin: true, + secure: false, + onProxyRes: (proxyRes, req, res) => { + let setCookie = proxyRes.headers['set-cookie']; + if (setCookie) { + setCookie[0] = setCookie[0].replace(/\bSecure\b(; )?/, ''); + } +} +})); - server.use(middlewares); - } - }; + server.use(middlewares); +} +}; return ServerConfig; } diff --git a/checkstyle-suppressions.xml b/checkstyle-suppressions.xml index b2a6be2211..34d06af649 100644 --- a/checkstyle-suppressions.xml +++ b/checkstyle-suppressions.xml @@ -40,5 +40,7 @@ - + + + \ No newline at end of file diff --git a/common-app-api/pom.xml b/common-app-api/pom.xml index 94196bb1af..9821b6b040 100644 --- a/common-app-api/pom.xml +++ b/common-app-api/pom.xml @@ -13,10 +13,9 @@ - org.openecomp.sdc - security-utils - ${project.version} - provided + org.onap.sdc.sdc-be-common + security-util-lib + ${security.util.version} @@ -210,18 +209,18 @@ commons-validator 1.6 - - commons-collections - commons-collections - - + + commons-collections + commons-collections + + - - commons-collections - commons-collections - 3.2.2 - + + commons-collections + commons-collections + 3.2.2 + org.codehaus.jettison @@ -235,6 +234,12 @@ 2.47 compile + + org.openecomp.sdc + common-app-logging + ${project.version} + compile + diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java index 0a3d50f848..75da11155b 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,417 +26,412 @@ import org.openecomp.sdc.common.config.IEcompConfigurationManager; public class BeEcompErrorManager extends AbsEcompErrorManager { - public enum ComponentName { - SERVICE, PRODUCT, VF - } - - public enum ErrorSeverity { - INFO, WARNING, ERROR, FATAL - } - - private static volatile BeEcompErrorManager instance; - private static ConfigurationManager configurationManager; - - private BeEcompErrorManager() { - } - - public static BeEcompErrorManager getInstance() { - if (instance == null) { - synchronized (BeEcompErrorManager.class) { - if (instance == null) { - instance = init(); - } - } - } - return instance; - } - - private static synchronized BeEcompErrorManager init() { - if (instance == null) { - instance = new BeEcompErrorManager(); - configurationManager = ConfigurationManager.getConfigurationManager(); - } - return instance; - } - - @Override - public IEcompConfigurationManager getConfigurationManager() { - return configurationManager; - } - - public void logBeUebAuthenticationError(String context, String reason) { - processEcompError(context, EcompErrorEnum.BeUebAuthenticationError, reason); - } - - public void logBeHealthCheckRecovery(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckRecovery); - } - - public void logBeHealthCheckJanusGraphRecovery(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckJanusGraphRecovery); - } - - public void logBeHealthCheckElasticSearchRecovery(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckElasticSearchRecovery); - } - - public void logBeHealthCheckUebClusterRecovery(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckUebClusterRecovery); - } - - public void logDmaapHealthCheckError(String context) { - processEcompError(context, EcompErrorEnum.DmaapHealthCheckError); - } - - public void logDmaapHealthCheckRecovery(String context) { - processEcompError(context, EcompErrorEnum.DmaapHealthCheckRecovery); - } - - public void logFeHealthCheckRecovery(String context) { - processEcompError(context, EcompErrorEnum.FeHealthCheckRecovery); - } - - public void logBeHealthCheckError(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckError); - } - - public void logBeHealthCheckJanusGraphError(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckJanusGraphError); - } - - public void logBeHealthCheckElasticSearchError(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckElasticSearchError); - } - - public void logBeHealthCheckUebClusterError(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckUebClusterError); - } - - public void logFeHealthCheckError(String context) { - processEcompError(context, EcompErrorEnum.FeHealthCheckError); - } - - /** - * @param context - * @param reason - */ - public void logBeUebConnectionError(String context, String reason) { - processEcompError(context, EcompErrorEnum.BeUebConnectionError, reason); - } - - public void logBeUebUnkownHostError(String context, String host) { - processEcompError(context, EcompErrorEnum.BeUebUnkownHostError, host); - } - - public void logBeComponentMissingError(String context, String componentType, String name) { - processEcompError(context, EcompErrorEnum.BeComponentMissingError, componentType, name); - } - - public void logBeIncorrectComponentError(String context, String componentType, String name) { - processEcompError(context, EcompErrorEnum.BeIncorrectComponentError, componentType, name); - } - - public void logBeInvalidConfigurationError(String context, String parameterName, String parameterValue) { - processEcompError(context, EcompErrorEnum.BeInvalidConfigurationError, parameterName, parameterValue); - } - - public void logBeUebObjectNotFoundError(String context, String notFoundObjectName) { - processEcompError(context, EcompErrorEnum.BeUebObjectNotFoundError, notFoundObjectName); - } - - public void logBeDistributionEngineInvalidArtifactType(String context, String artifactType, - String validArtifactTypes) { - processEcompError(context, EcompErrorEnum.BeDistributionEngineInvalidArtifactType, artifactType, - validArtifactTypes); - } - - public void logBeMissingConfigurationError(String context, String parameterName) { - processEcompError(context, EcompErrorEnum.BeMissingConfigurationError, parameterName); - } - - public void logBeConfigurationInvalidListSizeError(String context, String parameterName, int listMinimumSize) { - processEcompError(context, EcompErrorEnum.BeConfigurationInvalidListSizeError, parameterName, - String.valueOf(listMinimumSize)); - } - - public void logErrorConfigFileFormat(String context, String description) { - processEcompError(context, EcompErrorEnum.ErrorConfigFileFormat, description); - } - - public void logBeMissingArtifactInformationError(String context, String missingInfo) { - processEcompError(context, EcompErrorEnum.BeMissingArtifactInformationError, missingInfo); - } - - public void logBeArtifactMissingError(String context, String artifactName) { - processEcompError(context, EcompErrorEnum.BeArtifactMissingError, artifactName); - } - - public void logBeUserMissingError(String context, String userId) { - processEcompError(context, EcompErrorEnum.BeUserMissingError, userId); - } - - public void logBeInvalidTypeError(String context, String type, String name) { - processEcompError(context, EcompErrorEnum.BeInvalidTypeError, type, name); - } - - public void logBeInvalidValueError(String context, String value, String name, String type) { - processEcompError(context, EcompErrorEnum.BeInvalidValueError, value, name, type); - } - - public void logBeArtifactPayloadInvalid(String context) { - processEcompError(context, EcompErrorEnum.BeArtifactPayloadInvalid); - } - - public void logBeArtifactInformationInvalidError(String context) { - processEcompError(context, EcompErrorEnum.BeArtifactInformationInvalidError); - } - - public void logBeDistributionMissingError(String context, String distributionName) { - processEcompError(context, EcompErrorEnum.BeDistributionMissingError, "Distribution", distributionName); - } - - public void logBeGraphObjectMissingError(String context, String objectType, String objectName) { - processEcompError(context, EcompErrorEnum.BeGraphObjectMissingError, objectType, objectName); - } - - public void logBeInvalidJsonInput(String context) { - processEcompError(context, EcompErrorEnum.BeInvalidJsonInput); - } - - public void logBeInitializationError(String context) { - processEcompError(context, EcompErrorEnum.BeInitializationError); - } - - public void logBeFailedAddingResourceInstanceError(String context, String resourceName, String serviceId) { - processEcompError(context, EcompErrorEnum.BeFailedAddingResourceInstanceError, resourceName, serviceId); - } - - public void logBeUebSystemError(String context, String operation) { - processEcompError(context, EcompErrorEnum.BeUebSystemError, operation); - } - - public void logBeDistributionEngineSystemError(String context, String operation) { - processEcompError(context, EcompErrorEnum.BeDistributionEngineSystemError, operation); - } - - public void logBeFailedAddingNodeTypeError(String context, String nodeType) { - processEcompError(context, EcompErrorEnum.BeFailedAddingNodeTypeError, nodeType); - } - - public void logBeDaoSystemError(String context) { - processEcompError(context, EcompErrorEnum.BeDaoSystemError); - } - - public void logBeSystemError(String context) { - processEcompError(context, EcompErrorEnum.BeSystemError); - } - - public void logBeExecuteRollbackError(String context) { - processEcompError(context, EcompErrorEnum.BeExecuteRollbackError); - } - - public void logBeFailedLockObjectError(String context, String type, String id) { - processEcompError(context, EcompErrorEnum.BeFailedLockObjectError, type, id); - } - - public void logBeFailedCreateNodeError(String context, String nodeName, String status) { - processEcompError(context, EcompErrorEnum.BeFailedCreateNodeError, nodeName, status); - } - - public void logBeFailedUpdateNodeError(String context, String nodeName, String status) { - processEcompError(context, EcompErrorEnum.BeFailedUpdateNodeError, nodeName, status); - } - - public void logBeFailedDeleteNodeError(String context, String nodeName, String status) { - processEcompError(context, EcompErrorEnum.BeFailedDeleteNodeError, nodeName, status); - } - - public void logBeFailedRetrieveNodeError(String context, String nodeName, String status) { - processEcompError(context, EcompErrorEnum.BeFailedRetrieveNodeError, nodeName, status); - } - - public void logBeFailedFindParentError(String context, String node, String status) { - processEcompError(context, EcompErrorEnum.BeFailedFindParentError, node, status); - } - - public void logBeFailedFindAllNodesError(String context, String nodeType, String parentNode, String status) { - processEcompError(context, EcompErrorEnum.BeFailedFindAllNodesError, nodeType, parentNode, status); - } - - public void logBeFailedFindAssociationError(String context, String nodeType, String fromNode, String status) { - processEcompError(context, EcompErrorEnum.BeFailedFindAssociationError, nodeType, fromNode, status); - } - - public void logBeComponentCleanerSystemError(String context, String operation) { - processEcompError(context, EcompErrorEnum.BeComponentCleanerSystemError, operation); - } - - public void logBeRestApiGeneralError(String context) { - processEcompError(context, EcompErrorEnum.BeRestApiGeneralError); - } - - public void logFqdnResolveError(String context, String description) { - processEcompError(context, EcompErrorEnum.FqdnResolveError, description); - } - - public void logSiteSwitchoverInfo(String context, String description) { - processEcompError(context, EcompErrorEnum.SiteSwitchoverInfo, description); - } - - public void logInternalAuthenticationError(String context, String description, ErrorSeverity severity) { - - if (severity == null) { - processEcompError(context, EcompErrorEnum.InternalAuthenticationError, description); - } else { - switch (severity) { - case INFO: - processEcompError(context, EcompErrorEnum.InternalAuthenticationInfo, description); - break; - case WARNING: - processEcompError(context, EcompErrorEnum.InternalAuthenticationWarning, description); - break; - case ERROR: - processEcompError(context, EcompErrorEnum.InternalAuthenticationError, description); - break; - case FATAL: - processEcompError(context, EcompErrorEnum.InternalAuthenticationFatal, description); - break; - - default: - break; - } - } - - } - - public void logInternalConnectionError(String context, String description, ErrorSeverity severity) { - - if (severity == null) { - processEcompError(context, EcompErrorEnum.InternalConnectionError, description); - } else { - switch (severity) { - case INFO: - processEcompError(context, EcompErrorEnum.InternalConnectionInfo, description); - break; - case WARNING: - processEcompError(context, EcompErrorEnum.InternalConnectionWarning, description); - break; - case ERROR: - processEcompError(context, EcompErrorEnum.InternalConnectionError, description); - break; - case FATAL: - processEcompError(context, EcompErrorEnum.InternalConnectionFatal, description); - break; - - default: - break; - } - } - - } - - public void logInternalDataError(String context, String description, ErrorSeverity severity) { - - if (severity == null) { - processEcompError(context, EcompErrorEnum.InternalDataError, description); - } else { - switch (severity) { - case INFO: - processEcompError(context, EcompErrorEnum.InternalDataInfo, description); - break; - case WARNING: - processEcompError(context, EcompErrorEnum.InternalDataWarning, description); - break; - case ERROR: - processEcompError(context, EcompErrorEnum.InternalDataError, description); - break; - case FATAL: - processEcompError(context, EcompErrorEnum.InternalDataFatal, description); - break; - - default: - break; - } - } - - } - - public void logInvalidInputError(String context, String description, ErrorSeverity severity) { - - if (severity == null) { - processEcompError(context, EcompErrorEnum.InvalidInputError, description); - } else { - switch (severity) { - case INFO: - processEcompError(context, EcompErrorEnum.InvalidInputWarning, description); - break; - case WARNING: - processEcompError(context, EcompErrorEnum.InvalidInputInfo, description); - break; - case ERROR: - processEcompError(context, EcompErrorEnum.InvalidInputError, description); - break; - case FATAL: - processEcompError(context, EcompErrorEnum.InvalidInputFatal, description); - break; - - default: - break; - } - } - - } - - public void logInternalFlowError(String context, String description, ErrorSeverity severity) { - - if (severity == null) { - processEcompError(context, EcompErrorEnum.InternalFlowError, description); - } else { - switch (severity) { - case INFO: - processEcompError(context, EcompErrorEnum.InternalFlowInfo, description); - break; - case WARNING: - processEcompError(context, EcompErrorEnum.InternalFlowWarning, description); - break; - case ERROR: - processEcompError(context, EcompErrorEnum.InternalFlowError, description); - break; - case FATAL: - processEcompError(context, EcompErrorEnum.InternalFlowFatal, description); - break; - - default: - break; - } - } - - } - - public void logInternalUnexpectedError(String context, String description, ErrorSeverity severity) { - - if (severity == null) { - processEcompError(context, EcompErrorEnum.InternalUnexpectedError, description); - } else { - switch (severity) { - case INFO: - processEcompError(context, EcompErrorEnum.InternalUnexpectedInfo, description); - break; - case WARNING: - processEcompError(context, EcompErrorEnum.InternalUnexpectedWarning, description); - break; - case ERROR: - processEcompError(context, EcompErrorEnum.InternalUnexpectedError, description); - break; - case FATAL: - processEcompError(context, EcompErrorEnum.InternalUnexpectedFatal, description); - break; - - default: - break; - } - } - - } + public enum ComponentName { + SERVICE, PRODUCT, VF + } + + public enum ErrorSeverity { + INFO, WARNING, ERROR, FATAL + } + + private static volatile BeEcompErrorManager instance; + private static ConfigurationManager configurationManager; + + private BeEcompErrorManager() { + }; + + public static BeEcompErrorManager getInstance() { + if (instance == null) { + synchronized (BeEcompErrorManager.class){ + if (instance == null) + instance = init(); + } + } + return instance; + } + + private static synchronized BeEcompErrorManager init() { + if (instance == null) { + instance = new BeEcompErrorManager(); + configurationManager = ConfigurationManager.getConfigurationManager(); + } + return instance; + } + + @Override + public IEcompConfigurationManager getConfigurationManager() { + return configurationManager; + } + + public void logBeUebAuthenticationError(String context, String reason) { + processEcompError(context, EcompErrorEnum.BeUebAuthenticationError, reason); + } + + public void logBeHealthCheckRecovery(String context) { + processEcompError(context, EcompErrorEnum.BeHealthCheckRecovery); + } + + public void logBeHealthCheckJanusGraphRecovery(String context) { + processEcompError(context, EcompErrorEnum.BeHealthCheckJanusGraphRecovery); + } + + public void logBeHealthCheckUebClusterRecovery(String context) { + processEcompError(context, EcompErrorEnum.BeHealthCheckUebClusterRecovery); + } + + public void logDmaapHealthCheckError(String context) { + processEcompError(context, EcompErrorEnum.DmaapHealthCheckError); + } + + public void logUserSessionExpiredError(String context) { + processEcompError(context, EcompErrorEnum.SessionExpiredAuthenticationError); + } + + public void logDmaapHealthCheckRecovery(String context) { + processEcompError(context, EcompErrorEnum.DmaapHealthCheckRecovery); + } + + public void logFeHealthCheckRecovery(String context) { + processEcompError(context, EcompErrorEnum.FeHealthCheckRecovery); + } + + public void logBeHealthCheckError(String context) { + processEcompError(context, EcompErrorEnum.BeHealthCheckError); + } + + public void logBeHealthCheckJanusGraphError(String context) { + processEcompError(context, EcompErrorEnum.BeHealthCheckJanusGraphError); + } + + public void logBeHealthCheckUebClusterError(String context) { + processEcompError(context, EcompErrorEnum.BeHealthCheckUebClusterError); + } + + public void logFeHealthCheckError(String context) { + processEcompError(context, EcompErrorEnum.FeHealthCheckError); + } + + /** + * @param context + * @param reason + */ + public void logBeUebConnectionError(String context, String reason) { + processEcompError(context, EcompErrorEnum.BeUebConnectionError, reason); + } + + public void logBeUebUnkownHostError(String context, String host) { + processEcompError(context, EcompErrorEnum.BeUebUnkownHostError, host); + } + + public void logBeComponentMissingError(String context, String componentType, String name) { + processEcompError(context, EcompErrorEnum.BeComponentMissingError, componentType, name); + } + + public void logBeIncorrectComponentError(String context, String componentType, String name) { + processEcompError(context, EcompErrorEnum.BeIncorrectComponentError, componentType, name); + } + + public void logBeInvalidConfigurationError(String context, String parameterName, String parameterValue) { + processEcompError(context, EcompErrorEnum.BeInvalidConfigurationError, parameterName, parameterValue); + } + + public void logBeUebObjectNotFoundError(String context, String notFoundObjectName) { + processEcompError(context, EcompErrorEnum.BeUebObjectNotFoundError, notFoundObjectName); + } + + public void logBeDistributionEngineInvalidArtifactType(String context, String artifactType, + String validArtifactTypes) { + processEcompError(context, EcompErrorEnum.BeDistributionEngineInvalidArtifactType, artifactType, + validArtifactTypes); + } + + public void logBeMissingConfigurationError(String context, String parameterName) { + processEcompError(context, EcompErrorEnum.BeMissingConfigurationError, parameterName); + } + + public void logBeConfigurationInvalidListSizeError(String context, String parameterName, int listMinimumSize) { + processEcompError(context, EcompErrorEnum.BeConfigurationInvalidListSizeError, parameterName, + String.valueOf(listMinimumSize)); + } + + public void logErrorConfigFileFormat(String context, String description) { + processEcompError(context, EcompErrorEnum.ErrorConfigFileFormat, description); + } + + public void logBeMissingArtifactInformationError(String context, String missingInfo) { + processEcompError(context, EcompErrorEnum.BeMissingArtifactInformationError, missingInfo); + } + + public void logBeArtifactMissingError(String context, String artifactName) { + processEcompError(context, EcompErrorEnum.BeArtifactMissingError, artifactName); + } + + public void logBeUserMissingError(String context, String userId) { + processEcompError(context, EcompErrorEnum.BeUserMissingError, userId); + } + + public void logBeInvalidTypeError(String context, String type, String name) { + processEcompError(context, EcompErrorEnum.BeInvalidTypeError, type, name); + } + + public void logBeInvalidValueError(String context, String value, String name, String type) { + processEcompError(context, EcompErrorEnum.BeInvalidValueError, value, name, type); + } + + public void logBeArtifactPayloadInvalid(String context) { + processEcompError(context, EcompErrorEnum.BeArtifactPayloadInvalid); + } + + public void logBeArtifactInformationInvalidError(String context) { + processEcompError(context, EcompErrorEnum.BeArtifactInformationInvalidError); + } + + public void logBeDistributionMissingError(String context, String distributionName) { + processEcompError(context, EcompErrorEnum.BeDistributionMissingError, "Distribution", distributionName); + } + + public void logBeGraphObjectMissingError(String context, String objectType, String objectName) { + processEcompError(context, EcompErrorEnum.BeGraphObjectMissingError, objectType, objectName); + } + + public void logBeInvalidJsonInput(String context) { + processEcompError(context, EcompErrorEnum.BeInvalidJsonInput); + } + + public void logBeInitializationError(String context) { + processEcompError(context, EcompErrorEnum.BeInitializationError); + } + + public void logBeFailedAddingResourceInstanceError(String context, String resourceName, String serviceId) { + processEcompError(context, EcompErrorEnum.BeFailedAddingResourceInstanceError, resourceName, serviceId); + } + + public void logBeUebSystemError(String context, String operation) { + processEcompError(context, EcompErrorEnum.BeUebSystemError, operation); + } + + public void logBeDistributionEngineSystemError(String context, String operation) { + processEcompError(context, EcompErrorEnum.BeDistributionEngineSystemError, operation); + } + + public void logBeFailedAddingNodeTypeError(String context, String nodeType) { + processEcompError(context, EcompErrorEnum.BeFailedAddingNodeTypeError, nodeType); + } + + public void logBeDaoSystemError(String context) { + processEcompError(context, EcompErrorEnum.BeDaoSystemError); + } + + public void logBeSystemError(String context) { + processEcompError(context, EcompErrorEnum.BeSystemError); + } + + public void logBeExecuteRollbackError(String context) { + processEcompError(context, EcompErrorEnum.BeExecuteRollbackError); + } + + public void logBeFailedLockObjectError(String context, String type, String id) { + processEcompError(context, EcompErrorEnum.BeFailedLockObjectError, type, id); + } + + public void logBeFailedCreateNodeError(String context, String nodeName, String status) { + processEcompError(context, EcompErrorEnum.BeFailedCreateNodeError, nodeName, status); + } + + public void logBeFailedUpdateNodeError(String context, String nodeName, String status) { + processEcompError(context, EcompErrorEnum.BeFailedUpdateNodeError, nodeName, status); + } + + public void logBeFailedDeleteNodeError(String context, String nodeName, String status) { + processEcompError(context, EcompErrorEnum.BeFailedDeleteNodeError, nodeName, status); + } + + public void logBeFailedRetrieveNodeError(String context, String nodeName, String status) { + processEcompError(context, EcompErrorEnum.BeFailedRetrieveNodeError, nodeName, status); + } + + public void logBeFailedFindParentError(String context, String node, String status) { + processEcompError(context, EcompErrorEnum.BeFailedFindParentError, node, status); + } + + public void logBeFailedFindAllNodesError(String context, String nodeType, String parentNode, String status) { + processEcompError(context, EcompErrorEnum.BeFailedFindAllNodesError, nodeType, parentNode, status); + } + + public void logBeFailedFindAssociationError(String context, String nodeType, String fromNode, String status) { + processEcompError(context, EcompErrorEnum.BeFailedFindAssociationError, nodeType, fromNode, status); + } + + public void logBeComponentCleanerSystemError(String context, String operation) { + processEcompError(context, EcompErrorEnum.BeComponentCleanerSystemError, operation); + } + + public void logBeRestApiGeneralError(String context) { + processEcompError(context, EcompErrorEnum.BeRestApiGeneralError); + } + + public void logFqdnResolveError(String context, String description) { + processEcompError(context, EcompErrorEnum.FqdnResolveError, description); + } + + public void logSiteSwitchoverInfo(String context, String description) { + processEcompError(context, EcompErrorEnum.SiteSwitchoverInfo, description); + } + + public void logInternalAuthenticationError(String context, String description, ErrorSeverity severity) { + + if (severity == null) { + processEcompError(context, EcompErrorEnum.InternalAuthenticationError, description); + } else { + switch (severity) { + case INFO: + processEcompError(context, EcompErrorEnum.InternalAuthenticationInfo, description); + break; + case WARNING: + processEcompError(context, EcompErrorEnum.InternalAuthenticationWarning, description); + break; + case ERROR: + processEcompError(context, EcompErrorEnum.InternalAuthenticationError, description); + break; + case FATAL: + processEcompError(context, EcompErrorEnum.InternalAuthenticationFatal, description); + break; + + default: + break; + } + } + + } + + public void logInternalConnectionError(String context, String description, ErrorSeverity severity) { + + if (severity == null) { + processEcompError(context, EcompErrorEnum.InternalConnectionError, description); + } else { + switch (severity) { + case INFO: + processEcompError(context, EcompErrorEnum.InternalConnectionInfo, description); + break; + case WARNING: + processEcompError(context, EcompErrorEnum.InternalConnectionWarning, description); + break; + case ERROR: + processEcompError(context, EcompErrorEnum.InternalConnectionError, description); + break; + case FATAL: + processEcompError(context, EcompErrorEnum.InternalConnectionFatal, description); + break; + + default: + break; + } + } + + } + + public void logInternalDataError(String context, String description, ErrorSeverity severity) { + + if (severity == null) { + processEcompError(context, EcompErrorEnum.InternalDataError, description); + } else { + switch (severity) { + case INFO: + processEcompError(context, EcompErrorEnum.InternalDataInfo, description); + break; + case WARNING: + processEcompError(context, EcompErrorEnum.InternalDataWarning, description); + break; + case ERROR: + processEcompError(context, EcompErrorEnum.InternalDataError, description); + break; + case FATAL: + processEcompError(context, EcompErrorEnum.InternalDataFatal, description); + break; + + default: + break; + } + } + + } + + public void logInvalidInputError(String context, String description, ErrorSeverity severity) { + + if (severity == null) { + processEcompError(context, EcompErrorEnum.InvalidInputError, description); + } else { + switch (severity) { + case INFO: + processEcompError(context, EcompErrorEnum.InvalidInputWarning, description); + break; + case WARNING: + processEcompError(context, EcompErrorEnum.InvalidInputInfo, description); + break; + case ERROR: + processEcompError(context, EcompErrorEnum.InvalidInputError, description); + break; + case FATAL: + processEcompError(context, EcompErrorEnum.InvalidInputFatal, description); + break; + + default: + break; + } + } + + } + + public void logInternalFlowError(String context, String description, ErrorSeverity severity) { + + if (severity == null) { + processEcompError(context, EcompErrorEnum.InternalFlowError, description); + } else { + switch (severity) { + case INFO: + processEcompError(context, EcompErrorEnum.InternalFlowInfo, description); + break; + case WARNING: + processEcompError(context, EcompErrorEnum.InternalFlowWarning, description); + break; + case ERROR: + processEcompError(context, EcompErrorEnum.InternalFlowError, description); + break; + case FATAL: + processEcompError(context, EcompErrorEnum.InternalFlowFatal, description); + break; + + default: + break; + } + } + + } + + public void logInternalUnexpectedError(String context, String description, ErrorSeverity severity) { + + if (severity == null) { + processEcompError(context, EcompErrorEnum.InternalUnexpectedError, description); + } else { + switch (severity) { + case INFO: + processEcompError(context, EcompErrorEnum.InternalUnexpectedInfo, description); + break; + case WARNING: + processEcompError(context, EcompErrorEnum.InternalUnexpectedWarning, description); + break; + case ERROR: + processEcompError(context, EcompErrorEnum.InternalUnexpectedError, description); + break; + case FATAL: + processEcompError(context, EcompErrorEnum.InternalUnexpectedFatal, description); + break; + + default: + break; + } + } + + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/CadiFilterParams.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/CadiFilterParams.java new file mode 100644 index 0000000000..39793fb2cd --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/CadiFilterParams.java @@ -0,0 +1,142 @@ +package org.openecomp.sdc.be.config; + +public class CadiFilterParams { + + private String hostname; + private String csp_domain; + private String cadi_keyfile; + private String cadi_loglevel; + private String cadi_truststore; + private String cadi_truststore_password; + + private String aaf_id; + private String aaf_password; + private String aaf_env; + private String aafLocateUrl; + private String aaf_url; + private String AFT_LATITUDE; + private String AFT_LONGITUDE; + private String AFT_ENVIRONMENT; + private String cadiX509Issuers; + + public String getHostname() { + return hostname; + } + + public void setHostname(String hostname) { + this.hostname = hostname; + } + + public String getCsp_domain() { + return csp_domain; + } + + public void setCsp_domain(String csp_domain) { + this.csp_domain = csp_domain; + } + + public String getCadi_keyfile() { + return cadi_keyfile; + } + + public void setCadi_keyfile(String cadi_keyfile) { + this.cadi_keyfile = cadi_keyfile; + } + + public String getCadi_loglevel() { + return cadi_loglevel; + } + + public void setCadi_loglevel(String cadi_loglevel) { + this.cadi_loglevel = cadi_loglevel; + } + + public String getCadi_truststore() { + return cadi_truststore; + } + + public void setCadi_truststore(String cadi_truststore) { + this.cadi_truststore = cadi_truststore; + } + + public String getCadi_truststore_password() { + return cadi_truststore_password; + } + + public void setCadi_truststore_password(String cadi_truststore_password) { + this.cadi_truststore_password = cadi_truststore_password; + } + + public String getAaf_id() { + return aaf_id; + } + + public void setAaf_id(String aaf_id) { + this.aaf_id = aaf_id; + } + + public String getAaf_password() { + return aaf_password; + } + + public void setAaf_password(String aaf_password) { + this.aaf_password = aaf_password; + } + + public String getAaf_env() { + return aaf_env; + } + + public void setAaf_env(String aaf_env) { + this.aaf_env = aaf_env; + } + + public String getAafLocateUrl() { + return aafLocateUrl; + } + + public void setAafLocateUrl(String aafLocateUrl) { + this.aafLocateUrl = aafLocateUrl; + } + + public String getAaf_url() { + return aaf_url; + } + + public void setAaf_url(String aaf_url) { + this.aaf_url = aaf_url; + } + + public String getAFT_LATITUDE() { + return AFT_LATITUDE; + } + + public void setAFT_LATITUDE(String aFT_LATITUDE) { + AFT_LATITUDE = aFT_LATITUDE; + } + + public String getAFT_LONGITUDE() { + return AFT_LONGITUDE; + } + + public void setAFT_LONGITUDE(String aFT_LONGITUDE) { + AFT_LONGITUDE = aFT_LONGITUDE; + } + + public String getAFT_ENVIRONMENT() { + return AFT_ENVIRONMENT; + } + + public void setAFT_ENVIRONMENT(String aFT_ENVIRONMENT) { + AFT_ENVIRONMENT = aFT_ENVIRONMENT; + } + + public String getCadiX509Issuers() { + return cadiX509Issuers; + } + + public void setCadiX509Issuers(String cadiX509Issuers) { + this.cadiX509Issuers = cadiX509Issuers; + } + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/CleanComponentsConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/CleanComponentsConfiguration.java index dd0c6d0235..6411005449 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/CleanComponentsConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/CleanComponentsConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,23 +24,23 @@ import java.util.List; public class CleanComponentsConfiguration { - private long cleanIntervalInMinutes; - private List componentsToClean; + private long cleanIntervalInMinutes; + private List componentsToClean; - public long getCleanIntervalInMinutes() { - return cleanIntervalInMinutes; - } + public long getCleanIntervalInMinutes() { + return cleanIntervalInMinutes; + } - public void setCleanIntervalInMinutes(long cleanIntervalInMinutes) { - this.cleanIntervalInMinutes = cleanIntervalInMinutes; - } + public void setCleanIntervalInMinutes(long cleanIntervalInMinutes) { + this.cleanIntervalInMinutes = cleanIntervalInMinutes; + } - public List getComponentsToClean() { - return componentsToClean; - } + public List getComponentsToClean() { + return componentsToClean; + } - public void setComponentsToClean(List componentsToClean) { - this.componentsToClean = componentsToClean; - } + public void setComponentsToClean(List componentsToClean) { + this.componentsToClean = componentsToClean; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java index a51b42fb24..5d5afe0c98 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java @@ -68,7 +68,6 @@ public class Configuration extends BasicConfiguration { private List protocols; private Map users; private Map neo4j; - private ElasticSearchConfig elasticSearch; private String janusGraphCfgFile; private String janusGraphMigrationKeySpaceCfgFile; private Boolean janusGraphInMemoryGraph; @@ -77,7 +76,6 @@ public class Configuration extends BasicConfiguration { private Long janusGraphReconnectIntervalInSeconds; private List healthStatusExclude; private Long janusGraphHealthCheckReadTimeout; - private Long esReconnectIntervalInSeconds; private Long uebHealthCheckReconnectIntervalInSeconds; private Long uebHealthCheckReadTimeout; private List>> defaultImports; @@ -100,14 +98,12 @@ public class Configuration extends BasicConfiguration { private Map resourceInformationalDeployedArtifacts; private Map serviceApiArtifacts; private List excludeServiceCategory; - private Map> requirementsToFulfillBeforeCert; - private Map> capabilitiesToConsumeBeforeCert; private List artifactTypes; private List licenseTypes; private Integer additionalInformationMaxNumberOfKeys; - private Integer defaultHeatArtifactTimeoutMinutes; + private HeatDeploymentArtifactTimeout heatArtifactDeploymentTimeout; private BeMonitoringConfig systemMonitoring; private CleanComponentsConfiguration cleanComponentsConfiguration; @@ -136,25 +132,26 @@ public class Configuration extends BasicConfiguration { private boolean disableAudit; + private Boolean consumerBusinessLogic; + private Map vfModuleProperties; private Map genericAssetNodeTypes; private String appVersion; + private String artifactGeneratorConfig; - public String getAutoHealingOwner() { - return autoHealingOwner; - } + private CadiFilterParams cadiFilterParams; - public void setAutoHealingOwner(String autoHealingOwner) { - this.autoHealingOwner = autoHealingOwner; - } + private Boolean aafAuthNeeded; private String autoHealingOwner; private boolean enableAutoHealing; private Map> resourcesForUpgrade; private DmaapConsumerConfiguration dmaapConsumerConfiguration; + private DmaapProducerConfiguration dmaapProducerConfiguration; + private boolean skipUpgradeFailedVfs; private boolean skipUpgradeVSPs; private DmeConfiguration dmeConfiguration; @@ -162,6 +159,22 @@ public class Configuration extends BasicConfiguration { private boolean supportAllottedResourcesAndProxy; private Integer deleteLockTimeoutInSeconds; private Integer maxDeleteComponents; + private CookieConfig authCookie; + + + private String aafNamespace; + private String workloadContext; + + private EnvironmentContext environmentContext; + + + public String getAutoHealingOwner() { + return autoHealingOwner; + } + + public void setAutoHealingOwner(String autoHealingOwner) { + this.autoHealingOwner = autoHealingOwner; + } public Integer getMaxDeleteComponents() { return maxDeleteComponents; @@ -202,14 +215,9 @@ public class Configuration extends BasicConfiguration { public void setDmeConfiguration(DmeConfiguration dmeConfiguration) { this.dmeConfiguration = dmeConfiguration; } + public void setSkipUpgradeVSPs(boolean skipUpgradeVSPs) { this.skipUpgradeVSPs = skipUpgradeVSPs; } - public void setSkipUpgradeVSPs(boolean skipUpgradeVSPs) { - this.skipUpgradeVSPs = skipUpgradeVSPs; - } - - public boolean getSkipUpgradeVSPsFlag() { - return skipUpgradeVSPs; - } + public boolean getSkipUpgradeVSPsFlag() { return skipUpgradeVSPs; } public boolean getSkipUpgradeFailedVfs() { return skipUpgradeFailedVfs; @@ -235,9 +243,13 @@ public class Configuration extends BasicConfiguration { this.appVersion = appVersion; } - private String workloadContext; + public String getArtifactGeneratorConfig() { + return artifactGeneratorConfig; + } - private EnvironmentContext environmentContext; + public void setArtifactGeneratorConfig(String artifactGeneratorConfig) { + this.artifactGeneratorConfig = artifactGeneratorConfig; + } private List gabConfig; @@ -371,14 +383,6 @@ public class Configuration extends BasicConfiguration { this.neo4j = neo4j; } - public ElasticSearchConfig getElasticSearch() { - return elasticSearch; - } - - public void setElasticSearch(ElasticSearchConfig elasticSearch) { - this.elasticSearch = elasticSearch; - } - public String getJanusGraphCfgFile() { return janusGraphCfgFile; } @@ -443,18 +447,6 @@ public class Configuration extends BasicConfiguration { this.janusGraphReconnectIntervalInSeconds = janusGraphReconnectIntervalInSeconds; } - public Long getEsReconnectIntervalInSeconds() { - return esReconnectIntervalInSeconds; - } - - public Long getEsReconnectIntervalInSeconds(long defaultVal) { - return esReconnectIntervalInSeconds == null ? defaultVal : esReconnectIntervalInSeconds; - } - - public void setEsReconnectIntervalInSeconds(Long esReconnectIntervalInSeconds) { - this.esReconnectIntervalInSeconds = esReconnectIntervalInSeconds; - } - public List getArtifactTypes() { return artifactTypes; } @@ -576,20 +568,20 @@ public class Configuration extends BasicConfiguration { this.additionalInformationMaxNumberOfKeys = additionalInformationMaxNumberOfKeys; } - public BeMonitoringConfig getSystemMonitoring() { - return systemMonitoring; + public HeatDeploymentArtifactTimeout getHeatArtifactDeploymentTimeout() { + return heatArtifactDeploymentTimeout; } - public void setSystemMonitoring(BeMonitoringConfig systemMonitoring) { - this.systemMonitoring = systemMonitoring; + public void setHeatArtifactDeploymentTimeout(HeatDeploymentArtifactTimeout heatArtifactDeploymentTimeout) { + this.heatArtifactDeploymentTimeout = heatArtifactDeploymentTimeout; } - public Integer getDefaultHeatArtifactTimeoutMinutes() { - return defaultHeatArtifactTimeoutMinutes; + public BeMonitoringConfig getSystemMonitoring() { + return systemMonitoring; } - public void setDefaultHeatArtifactTimeoutMinutes(Integer defaultHeatArtifactTimeoutMinutes) { - this.defaultHeatArtifactTimeoutMinutes = defaultHeatArtifactTimeoutMinutes; + public void setSystemMonitoring(BeMonitoringConfig systemMonitoring) { + this.systemMonitoring = systemMonitoring; } public Long getUebHealthCheckReconnectIntervalInSeconds() { @@ -632,66 +624,128 @@ public class Configuration extends BasicConfiguration { this.gabConfig = gabConfig; } - public static class ElasticSearchConfig { - private List indicesTimeFrequency; + public static class CookieConfig { + String securityKey = ""; + long maxSessionTimeOut = 600*1000; + long sessionIdleTimeOut = 30*1000; + String cookieName = "AuthenticationCookie"; + String redirectURL = "https://www.e-access.att.com/ecomp_portal_ist/ecompportal/process_csp"; + List excludedUrls; + List onboardingExcludedUrls; + String domain = ""; + String path = ""; + boolean isHttpOnly = true; + + public String getSecurityKey() { + return securityKey; + } + + public void setSecurityKey(String securityKey) { + this.securityKey = securityKey; + } - public List getIndicesTimeFrequency() { - return indicesTimeFrequency; + public long getMaxSessionTimeOut() { + return maxSessionTimeOut; } - public void setIndicesTimeFrequency(List indicesTimeFrequency) { - this.indicesTimeFrequency = indicesTimeFrequency; + public void setMaxSessionTimeOut(long maxSessionTimeOut) { + this.maxSessionTimeOut = maxSessionTimeOut; } - public static class IndicesTimeFrequencyEntry { + public long getSessionIdleTimeOut() { + return sessionIdleTimeOut; + } - private String indexPrefix; - private String creationPeriod; + public void setSessionIdleTimeOut(long sessionIdleTimeOut) { + this.sessionIdleTimeOut = sessionIdleTimeOut; + } - public String getIndexPrefix() { - return indexPrefix; - } + public String getCookieName() { + return cookieName; + } - public void setIndexPrefix(String indexPrefix) { - this.indexPrefix = indexPrefix; - } + public void setCookieName(String cookieName) { + this.cookieName = cookieName; + } - public String getCreationPeriod() { - return creationPeriod; - } + public String getRedirectURL() { + return redirectURL; + } - public void setCreationPeriod(String creationPeriod) { - this.creationPeriod = creationPeriod; - } + public void setRedirectURL(String redirectURL) { + this.redirectURL = redirectURL; } - } - public static class CassandrConfig { - private static final Integer CASSANDRA_DEFAULT_PORT = 9042; + public List getExcludedUrls() { + return excludedUrls; + } + + public void setExcludedUrls(List excludedUrls) { + this.excludedUrls = excludedUrls; + } + + public String getDomain() { + return domain; + } - private List cassandraHosts; - private Integer cassandraPort; - private String localDataCenter; - private Long reconnectTimeout; - private Integer socketReadTimeout; - private Integer socketConnectTimeout; - private List keySpaces; - private boolean authenticate; - private String username; - private String password; - private boolean ssl; - private String truststorePath; - private String truststorePassword; + public void setDomain(String domain) { + this.domain = domain; + } - public Integer getCassandraPort() { - return cassandraPort != null ? cassandraPort : Configuration.CassandrConfig.CASSANDRA_DEFAULT_PORT; + public String getPath() { + return path; } - public void setCassandraPort(Integer cassandraPort) { - this.cassandraPort = cassandraPort; + public void setPath(String path) { + this.path = path; } + public boolean isHttpOnly() { + return isHttpOnly; + } + + public void setIsHttpOnly(boolean isHttpOnly) { + this.isHttpOnly = isHttpOnly; + } + + public List getOnboardingExcludedUrls() { + return onboardingExcludedUrls; + } + + public void setOnboardingExcludedUrls(List onboardingExcludedUrls) { + this.onboardingExcludedUrls = onboardingExcludedUrls; + } + } + + public CookieConfig getAuthCookie() { + return authCookie; + } + + public void setAuthCookie(CookieConfig authCookie) { + this.authCookie = authCookie; + } + + public static class CassandrConfig { + private static final Integer CASSANDRA_DEFAULT_PORT = 9042; + List cassandraHosts; + Integer cassandraPort; + String localDataCenter; + Long reconnectTimeout; + Integer socketReadTimeout; + Integer socketConnectTimeout; + List keySpaces; + boolean authenticate; + String username; + String password; + boolean ssl; + String truststorePath; + String truststorePassword; + + public Integer getCassandraPort() { return cassandraPort != null ? cassandraPort : Configuration.CassandrConfig.CASSANDRA_DEFAULT_PORT; } + + public void setCassandraPort(Integer cassandraPort) { this.cassandraPort = cassandraPort; } + public String getLocalDataCenter() { return localDataCenter; } @@ -756,21 +810,13 @@ public class Configuration extends BasicConfiguration { this.reconnectTimeout = reconnectTimeout; } - public Integer getSocketReadTimeout() { - return socketReadTimeout; - } + public Integer getSocketReadTimeout() { return socketReadTimeout; } - public void setSocketReadTimeout(Integer socketReadTimeout) { - this.socketReadTimeout = socketReadTimeout; - } + public void setSocketReadTimeout(Integer socketReadTimeout) { this.socketReadTimeout = socketReadTimeout;} - public Integer getSocketConnectTimeout() { - return socketConnectTimeout; - } + public Integer getSocketConnectTimeout() { return socketConnectTimeout;} - public void setSocketConnectTimeout(Integer socketConnectTimeout) { - this.socketConnectTimeout = socketConnectTimeout; - } + public void setSocketConnectTimeout(Integer socketConnectTimeout) { this.socketConnectTimeout = socketConnectTimeout; } public List getCassandraHosts() { return cassandraHosts; @@ -790,9 +836,9 @@ public class Configuration extends BasicConfiguration { public static class KeyspaceConfig { - private String name; - private String replicationStrategy; - private List replicationInfo; + String name; + String replicationStrategy; + List replicationInfo; public String getName() { return name; @@ -822,19 +868,19 @@ public class Configuration extends BasicConfiguration { public static class SwitchoverDetectorConfig { - private String gBeFqdn; - private String gFeFqdn; - private String beVip; - private String feVip; - private int beResolveAttempts; - private int feResolveAttempts; - private Boolean enabled; - private long interval; - private String changePriorityUser; - private String changePriorityPassword; - private String publishNetworkUrl; - private String publishNetworkBody; - private Map groups; + String gBeFqdn; + String gFeFqdn; + String beVip; + String feVip; + int beResolveAttempts; + int feResolveAttempts; + Boolean enabled; + long interval; + String changePriorityUser; + String changePriorityPassword; + String publishNetworkUrl; + String publishNetworkBody; + Map groups; public String getgBeFqdn() { return gBeFqdn; @@ -942,8 +988,8 @@ public class Configuration extends BasicConfiguration { public static class GroupInfo { - private String changePriorityUrl; - private String changePriorityBody; + String changePriorityUrl; + String changePriorityBody; public String getChangePriorityUrl() { return changePriorityUrl; @@ -964,11 +1010,46 @@ public class Configuration extends BasicConfiguration { } + public static class HeatDeploymentArtifactTimeout { + Integer defaultMinutes; + Integer minMinutes; + Integer maxMinutes; + + public Integer getDefaultMinutes() { + return defaultMinutes; + } + + public void setDefaultMinutes(Integer defaultMinutes) { + this.defaultMinutes = defaultMinutes; + } + + public Integer getMinMinutes() { + return minMinutes; + } + + public void setMinMinutes(Integer minMinutes) { + this.minMinutes = minMinutes; + } + + public Integer getMaxMinutes() { + return maxMinutes; + } + + public void setMaxMinutes(Integer maxMinutes) { + this.maxMinutes = maxMinutes; + } + + @Override + public String toString() { + return "HeatDeploymentArtifactTimeout config [default=" + defaultMinutes + ", min=" + minMinutes + ", max=" + maxMinutes + "]"; + } + } + public static class BeMonitoringConfig { - private Boolean enabled; - private Boolean isProxy; - private Integer probeIntervalInSeconds; + Boolean enabled; + Boolean isProxy; + Integer probeIntervalInSeconds; public Boolean getEnabled() { return enabled; @@ -1001,8 +1082,8 @@ public class Configuration extends BasicConfiguration { public static class ArtifactTypeConfig { - private List acceptedTypes; - private List validForResourceTypes; + List acceptedTypes; + List validForResourceTypes; public List getValidForResourceTypes() { return validForResourceTypes; @@ -1023,11 +1104,11 @@ public class Configuration extends BasicConfiguration { public static class OnboardingConfig { - private String protocol = "http"; - private String host; - private Integer port; - private String downloadCsarUri; - private String healthCheckUri; + String protocol = "http"; + String host; + Integer port; + String downloadCsarUri; + String healthCheckUri; public String getProtocol() { return protocol; @@ -1087,10 +1168,10 @@ public class Configuration extends BasicConfiguration { public static class DcaeConfig { - private String protocol = "http"; - private String host; - private Integer port; - private String healthCheckUri; + String protocol = "http"; + String host; + Integer port; + String healthCheckUri; public String getProtocol() { return protocol; @@ -1126,9 +1207,55 @@ public class Configuration extends BasicConfiguration { } public static class EcompPortalConfig { - + private String protocol = "https"; + private String host; + private Integer port; + private String healthCheckUri; private String defaultFunctionalMenu; + public void setPollingInterval(Integer pollingInterval) { + this.pollingInterval = pollingInterval; + } + + public void setTimeoutMs(Integer timeoutMs) { + this.timeoutMs = timeoutMs; + } + + private Integer pollingInterval; + private Integer timeoutMs; + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public Integer getPort() { + return port; + } + + public void setPort(Integer port) { + this.port = port; + } + + public String getHealthCheckUri() { + return healthCheckUri; + } + + public void setHealthCheckUri(String healthCheckUri) { + this.healthCheckUri = healthCheckUri; + } + public String getDefaultFunctionalMenu() { return defaultFunctionalMenu; } @@ -1137,6 +1264,14 @@ public class Configuration extends BasicConfiguration { this.defaultFunctionalMenu = defaultFunctionalMenu; } + public Integer getPollingInterval() { + return pollingInterval; + } + + public Integer getTimeoutMs() { + return timeoutMs; + } + @Override public String toString() { return "EcompPortalConfig [defaultFunctionalMenu=" + defaultFunctionalMenu + "]"; @@ -1146,7 +1281,7 @@ public class Configuration extends BasicConfiguration { public static class ApplicationL1CacheConfig { - private ApplicationL1CacheInfo datatypes; + ApplicationL1CacheInfo datatypes; public ApplicationL1CacheInfo getDatatypes() { return datatypes; @@ -1165,10 +1300,10 @@ public class Configuration extends BasicConfiguration { public static class ApplicationL2CacheConfig { - private boolean enabled; - private ApplicationL1CacheCatalogInfo catalogL1Cache; + boolean enabled; + ApplicationL1CacheCatalogInfo catalogL1Cache; - private QueueInfo queue; + QueueInfo queue; public boolean isEnabled() { return enabled; @@ -1222,9 +1357,9 @@ public class Configuration extends BasicConfiguration { public static class ApplicationL1CacheInfo { - private Boolean enabled; - private Integer firstRunDelay; - private Integer pollIntervalInSec; + Boolean enabled; + Integer firstRunDelay; + Integer pollIntervalInSec; public Boolean getEnabled() { return enabled; @@ -1259,10 +1394,10 @@ public class Configuration extends BasicConfiguration { public static class ApplicationL1CacheCatalogInfo { - private Boolean enabled; - private Integer resourcesSizeInCache; - private Integer servicesSizeInCache; - private Integer productsSizeInCache; + Boolean enabled; + Integer resourcesSizeInCache; + Integer servicesSizeInCache; + Integer productsSizeInCache; public Boolean getEnabled() { return enabled; @@ -1306,9 +1441,9 @@ public class Configuration extends BasicConfiguration { } public static class QueueInfo { - private Integer numberOfCacheWorkers; - private Integer waitOnShutDownInMinutes; - private Integer syncIntervalInSecondes; + Integer numberOfCacheWorkers; + Integer waitOnShutDownInMinutes; + Integer syncIntervalInSecondes; public Integer getWaitOnShutDownInMinutes() { return waitOnShutDownInMinutes; @@ -1343,8 +1478,8 @@ public class Configuration extends BasicConfiguration { public static class EnvironmentContext { - private String defaultValue; - private List validValues; + String defaultValue; + List validValues; public String getDefaultValue() { return defaultValue; @@ -1380,12 +1515,10 @@ public class Configuration extends BasicConfiguration { .append(format("backend protocol: %s%n", beProtocol)).append(format("Version: %s%n", version)) .append(format("Released: %s%n", released)).append(format("Supported protocols: %s%n", protocols)) .append(format("Users: %s%n", users)).append(format("Neo4j: %s%n", neo4j)) - .append(format("ElasticSearch: %s%n", elasticSearch)) .append(format("JanusGraph Cfg File: %s%n", janusGraphCfgFile)) .append(format("JanusGraph In memory: %s%n", janusGraphInMemoryGraph)) .append(format("JanusGraph lock timeout: %s%n", janusGraphLockTimeout)) - .append(format("JanusGraph reconnect interval seconds: %s%n", - janusGraphReconnectIntervalInSeconds)) + .append(format("JanusGraph reconnect interval seconds: %s%n", janusGraphReconnectIntervalInSeconds)) .append(format("excludeResourceCategory: %s%n", excludeResourceCategory)) .append(format("informationalResourceArtifacts: %s%n", informationalResourceArtifacts)) .append(format("deploymentResourceArtifacts: %s%n", deploymentResourceArtifacts)) @@ -1394,14 +1527,12 @@ public class Configuration extends BasicConfiguration { .append(format("Supported license types: %s%n", licenseTypes)) .append(format("Additional information Maximum number of preoperties: %s%n", additionalInformationMaxNumberOfKeys)) - .append(format("Default Heat Artifact Timeout in Minutes: %s%n", defaultHeatArtifactTimeoutMinutes)) + .append(format("Heat Artifact Timeout in Minutes: %s%n", heatArtifactDeploymentTimeout)) .append(format("URLs For HTTP Requests that will not be automatically logged : %s%n", unLoggedUrls)) .append(format("Service Api Artifacts: %s%n", serviceApiArtifacts)) .append(format("heat env artifact header: %s%n", heatEnvArtifactHeader)) .append(format("heat env artifact footer: %s%n", heatEnvArtifactFooter)) - .append(format("onboarding: %s%n", onboarding)) - .append(format("tosca conformance level: %s%n", toscaConformanceLevel)) - .toString(); + .append(format("onboarding: %s%n", onboarding)).toString(); } public List getUnLoggedUrls() { @@ -1485,22 +1616,6 @@ public class Configuration extends BasicConfiguration { this.heatTranslatorPath = heatTranslatorPath; } - public Map> getRequirementsToFulfillBeforeCert() { - return requirementsToFulfillBeforeCert; - } - - public void setRequirementsToFulfillBeforeCert(Map> requirementsToFulfillBeforeCert) { - this.requirementsToFulfillBeforeCert = requirementsToFulfillBeforeCert; - } - - public Map> getCapabilitiesToConsumeBeforeCert() { - return capabilitiesToConsumeBeforeCert; - } - - public void setCapabilitiesToConsumeBeforeCert(Map> capabilitiesToConsumeBeforeCert) { - this.capabilitiesToConsumeBeforeCert = capabilitiesToConsumeBeforeCert; - } - public OnboardingConfig getOnboarding() { return onboarding; } @@ -1529,6 +1644,14 @@ public class Configuration extends BasicConfiguration { return disableAudit; } + public Boolean getConsumerBusinessLogic() { + return consumerBusinessLogic; + } + + public void setConsumerBusinessLogic(Boolean consumerBusinessLogic) { + this.consumerBusinessLogic = consumerBusinessLogic; + } + public void setDisableAudit(boolean enableAudit) { this.disableAudit = enableAudit; } @@ -1568,19 +1691,15 @@ public class Configuration extends BasicConfiguration { public static class VfModuleProperty { private String forBaseModule; private String forNonBaseModule; - public String getForBaseModule() { return forBaseModule; } - public void setForBaseModule(String forBaseModule) { this.forBaseModule = forBaseModule; } - public String getForNonBaseModule() { return forNonBaseModule; } - public void setForNonBaseModule(String forNonBaseModule) { this.forNonBaseModule = forNonBaseModule; } @@ -1603,7 +1722,7 @@ public class Configuration extends BasicConfiguration { } @SuppressWarnings("unchecked") - public static Map safeGetCapsInsensitiveMap(Map map) { + public static Map safeGetCapsInsensitiveMap(Map map) { return map == null ? emptyMap() : new CaseInsensitiveMap(map); } @@ -1616,6 +1735,38 @@ public class Configuration extends BasicConfiguration { this.healthStatusExclude = healthStatusExclude; } + public DmaapProducerConfiguration getDmaapProducerConfiguration() { + return dmaapProducerConfiguration; + } + + public void setDmaapProducerConfiguration(DmaapProducerConfiguration dmaapProducerConfiguration) { + this.dmaapProducerConfiguration = dmaapProducerConfiguration; + } + + public String getAafNamespace() { + return aafNamespace; + } + + public void setAafNamespace(String aafNamespace) { + this.aafNamespace = aafNamespace; + } + + public Boolean getAafAuthNeeded(){ + return aafAuthNeeded; + } + + public void setAafAuthNeeded(Boolean aafAuthNeeded){ + this.aafAuthNeeded = aafAuthNeeded; + } + + public CadiFilterParams getCadiFilterParams() { + return cadiFilterParams; + } + + public void setCadiFilterParams(CadiFilterParams cadiFilterParams) { + this.cadiFilterParams = cadiFilterParams; + } + public static class PathsAndNamesDefinition { private String friendlyName; @@ -1667,4 +1818,5 @@ public class Configuration extends BasicConfiguration { this.pathsAndNamesDefinitions = pathsAndNamesDefinitions; } } + } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ConfigurationManager.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ConfigurationManager.java index 9920b597a1..0e9fd24111 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ConfigurationManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ConfigurationManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -33,121 +33,113 @@ import java.util.Map; public class ConfigurationManager implements FileChangeCallback, IEcompConfigurationManager { + + ConfigurationSource configurationSource = null; + private static ConfigurationManager instance; + @VisibleForTesting public ConfigurationManager() { super(); instance = this; } - private ConfigurationSource configurationSource = null; - private static ConfigurationManager instance; - - public Map getConfigurations() { - return configurations; - } - - public void setConfigurations(Map configurations) { - this.configurations = configurations; - } - - private Map configurations = new HashMap<>(); - - public ConfigurationManager(ConfigurationSource configurationSource) { - super(); - this.configurationSource = configurationSource; - loadConfigurationFiles(); - instance = this; - } + Map configurations = new HashMap<>(); + public ConfigurationManager(ConfigurationSource configurationSource) { + super(); + this.configurationSource = configurationSource; + loadConfigurationFiles(); + instance = this; + } - private void loadConfigurationFiles() { + private void loadConfigurationFiles() { - loadConfigurationClass(Configuration.class); - loadConfigurationClass(ErrorConfiguration.class); - loadConfigurationClass(Neo4jErrorsConfiguration.class); - loadConfigurationClass(EcompErrorConfiguration.class); - loadConfigurationClass(DistributionEngineConfiguration.class); - } + loadConfigurationClass(Configuration.class); + loadConfigurationClass(ErrorConfiguration.class); + loadConfigurationClass(Neo4jErrorsConfiguration.class); + loadConfigurationClass(EcompErrorConfiguration.class); + loadConfigurationClass(DistributionEngineConfiguration.class); + } - private void loadConfigurationClass(Class clazz) { - ConfigurationListener configurationListener = new ConfigurationListener(clazz, this); + private void loadConfigurationClass(Class clazz) { + ConfigurationListener configurationListener = new ConfigurationListener(clazz, this); - T object = configurationSource.getAndWatchConfiguration(clazz, configurationListener); + T object = configurationSource.getAndWatchConfiguration(clazz, configurationListener); - configurations.put(getKey(clazz), object); - } + configurations.put(getKey(clazz), object); + } - private String getKey(Class class1) { + private String getKey(Class class1) { - return class1.getSimpleName(); + return class1.getSimpleName(); - } + } - public Configuration getConfiguration() { + public Configuration getConfiguration() { - return (Configuration) configurations.get(getKey(Configuration.class)); + return (Configuration) configurations.get(getKey(Configuration.class)); - } + } - public void setConfiguration(Configuration configuration) { + public void setConfiguration(Configuration configuration) { - configurations.put(getKey(Configuration.class), configuration); + configurations.put(getKey(Configuration.class), configuration); - } + } - public void setErrorConfiguration(ErrorConfiguration configuration) { + public void setErrorConfiguration(ErrorConfiguration configuration) { - configurations.put(getKey(ErrorConfiguration.class), configuration); + configurations.put(getKey(ErrorConfiguration.class), configuration); - } + } - public ErrorConfiguration getErrorConfiguration() { + public ErrorConfiguration getErrorConfiguration() { - return (ErrorConfiguration) configurations.get(getKey(ErrorConfiguration.class)); + return (ErrorConfiguration) configurations.get(getKey(ErrorConfiguration.class)); - } + } - public Neo4jErrorsConfiguration getNeo4jErrorsConfiguration() { - return (Neo4jErrorsConfiguration) configurations.get(getKey(Neo4jErrorsConfiguration.class)); - } + public Neo4jErrorsConfiguration getNeo4jErrorsConfiguration() { + return (Neo4jErrorsConfiguration) configurations.get(getKey(Neo4jErrorsConfiguration.class)); + } - @Override - public EcompErrorConfiguration getEcompErrorConfiguration() { + @Override + public EcompErrorConfiguration getEcompErrorConfiguration() { - return (EcompErrorConfiguration) configurations.get(getKey(EcompErrorConfiguration.class)); + return (EcompErrorConfiguration) configurations.get(getKey(EcompErrorConfiguration.class)); - } + } - public Configuration getConfigurationAndWatch(ConfigurationListener configurationListener) { + public Configuration getConfigurationAndWatch(ConfigurationListener configurationListener) { - if (configurationListener != null) { + if (configurationListener != null) { - configurationSource.addWatchConfiguration(Configuration.class, configurationListener); + configurationSource.addWatchConfiguration(Configuration.class, configurationListener); - } - return (Configuration) configurations.get(getKey(Configuration.class)); + } + return (Configuration) configurations.get(getKey(Configuration.class)); - } + } - public static ConfigurationManager getConfigurationManager() { - return instance; - } + public static ConfigurationManager getConfigurationManager() { + return instance; + } public void reconfigure(BasicConfiguration obj) { } - /** - * FOR TEST ONLY - * - * @param ecompErrorConfiguration - */ - public void setEcompErrorConfiguration(EcompErrorConfiguration ecompErrorConfiguration) { + /** + * FOR TEST ONLY + * + * @param ecompErrorConfiguration + */ + public void setEcompErrorConfiguration(EcompErrorConfiguration ecompErrorConfiguration) { - configurations.put(getKey(EcompErrorConfiguration.class), ecompErrorConfiguration); + configurations.put(getKey(EcompErrorConfiguration.class), ecompErrorConfiguration); - } + } - public DistributionEngineConfiguration getDistributionEngineConfiguration() { + public DistributionEngineConfiguration getDistributionEngineConfiguration() { - return (DistributionEngineConfiguration) configurations.get(getKey(DistributionEngineConfiguration.class)); + return (DistributionEngineConfiguration) configurations.get(getKey(DistributionEngineConfiguration.class)); - } + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java index b7b0e64189..b23e076334 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,461 +23,449 @@ package org.openecomp.sdc.be.config; import org.openecomp.sdc.common.api.BasicConfiguration; import org.openecomp.sdc.common.http.config.ExternalServiceConfig; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; public class DistributionEngineConfiguration extends BasicConfiguration { - private List uebServers; + private List uebServers; - private String distributionNotifTopicName; + private String distributionNotifTopicName; - private String distributionStatusTopicName; + private String distributionStatusTopicName; - private Integer initRetryIntervalSec; + private Integer initRetryIntervalSec; - private Integer initMaxIntervalSec; + private Integer initMaxIntervalSec; - private ComponentArtifactTypesConfig distribNotifServiceArtifactTypes; + private ComponentArtifactTypesConfig distribNotifServiceArtifactTypes; - private ComponentArtifactTypesConfig distribNotifResourceArtifactTypes; + private ComponentArtifactTypesConfig distribNotifResourceArtifactTypes; - private String uebPublicKey; + private String uebPublicKey; - private String uebSecretKey; + private String uebSecretKey; - private List environments; + private List environments; - private DistributionStatusTopicConfig distributionStatusTopic; + private DistributionStatusTopicConfig distributionStatusTopic; - private CreateTopicConfig createTopic; + private CreateTopicConfig createTopic; - private boolean startDistributionEngine; + private boolean startDistributionEngine; - private DistributionNotificationTopicConfig distributionNotificationTopic; + private DistributionNotificationTopicConfig distributionNotificationTopic; - private Integer defaultArtifactInstallationTimeout = 60; + private Integer defaultArtifactInstallationTimeout = 60; + + private Integer currentArtifactInstallationTimeout = 120; + private boolean useHttpsWithDmaap; - private Integer currentArtifactInstallationTimeout = 120; + private ExternalServiceConfig aaiConfig; - private boolean useHttpsWithDmaap; + private ExternalServiceConfig msoConfig; + + private Integer opEnvRecoveryIntervalSec; + + private Integer allowedTimeBeforeStaleSec; + + public static class DistribNotifServiceArtifacts { - private ExternalServiceConfig aaiConfig; + Map service; + Map resource; + + - private ExternalServiceConfig msoConfig; + public Map getService() { + return service; + } - private Integer opEnvRecoveryIntervalSec; + public void setService(Map service) { + this.service = service; + } - private Integer allowedTimeBeforeStaleSec; + public Map getResource() { + return resource; + } - public static class DistribNotifServiceArtifacts { + public void setResource(Map resource) { + this.resource = resource; + } - private Map service; - private Map resource; + } + public static class NotifArtifactTypes { - public Map getService() { - return service; - } + List info; + List lifecycle; - public void setService(Map service) { - this.service = service; - } + public List getInfo() { + return info; + } - public Map getResource() { - return resource; - } + public void setInfo(List info) { + this.info = info; + } - public void setResource(Map resource) { - this.resource = resource; - } + public List getLifecycle() { + return lifecycle; + } - } - - public static class NotifArtifactTypes { - - private List info; - private List lifecycle; - - public List getInfo() { - return info; - } - - public void setInfo(List info) { - this.info = info; - } - - public List getLifecycle() { - return lifecycle; - } - - public void setLifecycle(List lifecycle) { - this.lifecycle = lifecycle; - } + public void setLifecycle(List lifecycle) { + this.lifecycle = lifecycle; + } - } - - public static class NotifArtifactTypesResource { + } - private List lifecycle; + public static class NotifArtifactTypesResource { - public List getLifecycle() { - return lifecycle; - } - - public void setLifecycle(List lifecycle) { - this.lifecycle = lifecycle; - } - } + List lifecycle; - public enum ArtifcatTypeEnum { + } - MURANO_PKG("MURANO-PKG"), HEAT("HEAT"), DG_XML("DG_XML"); + public enum ArtifcatTypeEnum { - private String value; + MURANO_PKG("MURANO-PKG"), HEAT("HEAT"), DG_XML("DG_XML"); - ArtifcatTypeEnum(String value) { - this.value = value; - } + String value; - public String getValue() { + private ArtifcatTypeEnum(String value) { + this.value = value; + } - return value; - } - } - - public List getUebServers() { - return uebServers; - } + public String getValue() { - public void setUebServers(List uebServers) { - this.uebServers = uebServers; - } + return value; + } + } - public String getDistributionNotifTopicName() { - return distributionNotifTopicName; - } + public List getUebServers() { + return uebServers; + } - public void setDistributionNotifTopicName(String distributionNotifTopicName) { - this.distributionNotifTopicName = distributionNotifTopicName; - } + public void setUebServers(List uebServers) { + this.uebServers = uebServers; + } - public String getDistributionStatusTopicName() { - return distributionStatusTopicName; - } + public String getDistributionNotifTopicName() { + return distributionNotifTopicName; + } - public void setDistributionStatusTopicName(String distributionStatusTopicName) { - this.distributionStatusTopicName = distributionStatusTopicName; - } + public void setDistributionNotifTopicName(String distributionNotifTopicName) { + this.distributionNotifTopicName = distributionNotifTopicName; + } - public Integer getInitRetryIntervalSec() { - return initRetryIntervalSec; - } + public String getDistributionStatusTopicName() { + return distributionStatusTopicName; + } - public void setInitRetryIntervalSec(Integer initRetryIntervalSec) { - this.initRetryIntervalSec = initRetryIntervalSec; - } + public void setDistributionStatusTopicName(String distributionStatusTopicName) { + this.distributionStatusTopicName = distributionStatusTopicName; + } - public ComponentArtifactTypesConfig getDistribNotifServiceArtifactTypes() { - return distribNotifServiceArtifactTypes; - } + public Integer getInitRetryIntervalSec() { + return initRetryIntervalSec; + } - public void setDistribNotifServiceArtifactTypes(ComponentArtifactTypesConfig distribNotifServiceArtifactTypes) { - this.distribNotifServiceArtifactTypes = distribNotifServiceArtifactTypes; - } + public void setInitRetryIntervalSec(Integer initRetryIntervalSec) { + this.initRetryIntervalSec = initRetryIntervalSec; + } - public ComponentArtifactTypesConfig getDistribNotifResourceArtifactTypes() { - return distribNotifResourceArtifactTypes; - } + public ComponentArtifactTypesConfig getDistribNotifServiceArtifactTypes() { + return distribNotifServiceArtifactTypes; + } - public void setDistribNotifResourceArtifactTypes(ComponentArtifactTypesConfig distribNotifResourceArtifactTypes) { - this.distribNotifResourceArtifactTypes = distribNotifResourceArtifactTypes; - } + public void setDistribNotifServiceArtifactTypes(ComponentArtifactTypesConfig distribNotifServiceArtifactTypes) { + this.distribNotifServiceArtifactTypes = distribNotifServiceArtifactTypes; + } - public String getUebPublicKey() { - return uebPublicKey; - } + public ComponentArtifactTypesConfig getDistribNotifResourceArtifactTypes() { + return distribNotifResourceArtifactTypes; + } - public void setUebPublicKey(String uebPublicKey) { - this.uebPublicKey = uebPublicKey; - } + public void setDistribNotifResourceArtifactTypes(ComponentArtifactTypesConfig distribNotifResourceArtifactTypes) { + this.distribNotifResourceArtifactTypes = distribNotifResourceArtifactTypes; + } - public String getUebSecretKey() { - return uebSecretKey; - } + public String getUebPublicKey() { + return uebPublicKey; + } - public void setUebSecretKey(String uebSecretKey) { - this.uebSecretKey = uebSecretKey; - } + public void setUebPublicKey(String uebPublicKey) { + this.uebPublicKey = uebPublicKey; + } - public List getEnvironments() { - return environments; - } + public String getUebSecretKey() { + return uebSecretKey; + } - public void setEnvironments(List environments) { + public void setUebSecretKey(String uebSecretKey) { + this.uebSecretKey = uebSecretKey; + } - Set set = new HashSet<>(); - if (environments != null) { - set.addAll(environments); - this.environments = new ArrayList<>(set); - } else { - this.environments = null; - } + public List getEnvironments() { + return environments; + } - } + public void setEnvironments(List environments) { - public DistributionStatusTopicConfig getDistributionStatusTopic() { - return distributionStatusTopic; - } + Set set = new HashSet<>(); + if (environments != null) { + set.addAll(environments); + this.environments = new ArrayList<>(set); + } else { + this.environments = null; + } - public void setDistributionStatusTopic(DistributionStatusTopicConfig distributionStatusTopic) { - this.distributionStatusTopic = distributionStatusTopic; - } + } - public Integer getInitMaxIntervalSec() { - return initMaxIntervalSec; - } + public DistributionStatusTopicConfig getDistributionStatusTopic() { + return distributionStatusTopic; + } - public void setInitMaxIntervalSec(Integer initMaxIntervalSec) { - this.initMaxIntervalSec = initMaxIntervalSec; - } + public void setDistributionStatusTopic(DistributionStatusTopicConfig distributionStatusTopic) { + this.distributionStatusTopic = distributionStatusTopic; + } - public CreateTopicConfig getCreateTopic() { - return createTopic; - } + public Integer getInitMaxIntervalSec() { + return initMaxIntervalSec; + } - public void setCreateTopic(CreateTopicConfig createTopic) { - this.createTopic = createTopic; - } + public void setInitMaxIntervalSec(Integer initMaxIntervalSec) { + this.initMaxIntervalSec = initMaxIntervalSec; + } - public boolean isStartDistributionEngine() { - return startDistributionEngine; - } + public CreateTopicConfig getCreateTopic() { + return createTopic; + } - public void setStartDistributionEngine(boolean startDistributionEngine) { - this.startDistributionEngine = startDistributionEngine; - } + public void setCreateTopic(CreateTopicConfig createTopic) { + this.createTopic = createTopic; + } - public DistributionNotificationTopicConfig getDistributionNotificationTopic() { - return distributionNotificationTopic; - } + public boolean isStartDistributionEngine() { + return startDistributionEngine; + } - public void setDistributionNotificationTopic(DistributionNotificationTopicConfig distributionNotificationTopic) { - this.distributionNotificationTopic = distributionNotificationTopic; - } + public void setStartDistributionEngine(boolean startDistributionEngine) { + this.startDistributionEngine = startDistributionEngine; + } - public int getDefaultArtifactInstallationTimeout() { - return defaultArtifactInstallationTimeout; - } - public void setDefaultArtifactInstallationTimeout(int defaultArtifactInstallationTimeout) { - this.defaultArtifactInstallationTimeout = defaultArtifactInstallationTimeout; - } - public int getCurrentArtifactInstallationTimeout() { - return currentArtifactInstallationTimeout; - } + public DistributionNotificationTopicConfig getDistributionNotificationTopic() { + return distributionNotificationTopic; + } - public void setCurrentArtifactInstallationTimeout(int currentArtifactInstallationTimeout) { - this.currentArtifactInstallationTimeout = currentArtifactInstallationTimeout; - } + public void setDistributionNotificationTopic(DistributionNotificationTopicConfig distributionNotificationTopic) { + this.distributionNotificationTopic = distributionNotificationTopic; + } - public boolean isUseHttpsWithDmaap() { - return useHttpsWithDmaap; - } + public int getDefaultArtifactInstallationTimeout() { + return defaultArtifactInstallationTimeout; + } + public void setDefaultArtifactInstallationTimeout(int defaultArtifactInstallationTimeout) { + this.defaultArtifactInstallationTimeout = defaultArtifactInstallationTimeout; + } + + public int getCurrentArtifactInstallationTimeout() { + return currentArtifactInstallationTimeout; + } + public void setCurrentArtifactInstallationTimeout(int currentArtifactInstallationTimeout) { + this.currentArtifactInstallationTimeout = currentArtifactInstallationTimeout; + } + public boolean isUseHttpsWithDmaap() { + return useHttpsWithDmaap; + } - public void setUseHttpsWithDmaap(boolean useHttpsWithDmaap) { - this.useHttpsWithDmaap = useHttpsWithDmaap; - } + public void setUseHttpsWithDmaap(boolean useHttpsWithDmaap) { + this.useHttpsWithDmaap = useHttpsWithDmaap; + } - public static class CreateTopicConfig { + public static class CreateTopicConfig { - private Integer partitionCount; - private Integer replicationCount; + private Integer partitionCount; + private Integer replicationCount; - public Integer getPartitionCount() { - return partitionCount; - } + public Integer getPartitionCount() { + return partitionCount; + } - public void setPartitionCount(Integer partitionCount) { - this.partitionCount = partitionCount; - } + public void setPartitionCount(Integer partitionCount) { + this.partitionCount = partitionCount; + } - public Integer getReplicationCount() { - return replicationCount; - } + public Integer getReplicationCount() { + return replicationCount; + } - public void setReplicationCount(Integer replicationCount) { - this.replicationCount = replicationCount; - } + public void setReplicationCount(Integer replicationCount) { + this.replicationCount = replicationCount; + } - @Override - public String toString() { - return "CreateTopicConfig [partitionCount=" + partitionCount + ", replicationCount=" + replicationCount - + "]"; - } + @Override + public String toString() { + return "CreateTopicConfig [partitionCount=" + partitionCount + ", replicationCount=" + replicationCount + + "]"; + } - } + } - public static class EnvironmentConfig { + public static class EnvironmentConfig { - private String name; - private List uebServers; + private String name; + private List uebServers; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public List getUebServers() { - return uebServers; - } + public List getUebServers() { + return uebServers; + } - public void setUebServers(List uebServers) { - this.uebServers = uebServers; - } + public void setUebServers(List uebServers) { + this.uebServers = uebServers; + } - @Override - public String toString() { - return "EnvironmentConfig [name=" + name + ", uebServers=" + uebServers + "]"; - } + @Override + public String toString() { + return "EnvironmentConfig [name=" + name + ", uebServers=" + uebServers + "]"; + } - } + } - public static class DistributionStatusTopicConfig { + public static class DistributionStatusTopicConfig { - private Integer pollingIntervalSec; - private Integer fetchTimeSec; - private String consumerGroup; - private String consumerId; + private Integer pollingIntervalSec; + private Integer fetchTimeSec; + private String consumerGroup; + private String consumerId; - public Integer getPollingIntervalSec() { - return pollingIntervalSec; - } + public Integer getPollingIntervalSec() { + return pollingIntervalSec; + } - public void setPollingIntervalSec(Integer pollingIntervalSec) { - this.pollingIntervalSec = pollingIntervalSec; - } + public void setPollingIntervalSec(Integer pollingIntervalSec) { + this.pollingIntervalSec = pollingIntervalSec; + } - public Integer getFetchTimeSec() { - return fetchTimeSec; - } + public Integer getFetchTimeSec() { + return fetchTimeSec; + } - public void setFetchTimeSec(Integer fetchTimeSec) { - this.fetchTimeSec = fetchTimeSec; - } + public void setFetchTimeSec(Integer fetchTimeSec) { + this.fetchTimeSec = fetchTimeSec; + } - public String getConsumerGroup() { - return consumerGroup; - } + public String getConsumerGroup() { + return consumerGroup; + } - public void setConsumerGroup(String consumerGroup) { - this.consumerGroup = consumerGroup; - } + public void setConsumerGroup(String consumerGroup) { + this.consumerGroup = consumerGroup; + } - public String getConsumerId() { - return consumerId; - } + public String getConsumerId() { + return consumerId; + } - public void setConsumerId(String consumerId) { - this.consumerId = consumerId; - } + public void setConsumerId(String consumerId) { + this.consumerId = consumerId; + } - @Override - public String toString() { - return "DistributionStatusTopicConfig [pollingIntervalSec=" + pollingIntervalSec + ", fetchTimeSec=" - + fetchTimeSec + ", consumerGroup=" + consumerGroup + ", consumerId=" + consumerId + "]"; - } + @Override + public String toString() { + return "DistributionStatusTopicConfig [pollingIntervalSec=" + pollingIntervalSec + ", fetchTimeSec=" + + fetchTimeSec + ", consumerGroup=" + consumerGroup + ", consumerId=" + consumerId + "]"; + } - } + } - public static class DistributionNotificationTopicConfig { + public static class DistributionNotificationTopicConfig { - private Integer maxWaitingAfterSendingSeconds; - private Integer maxThreadPoolSize; - private Integer minThreadPoolSize; + private Integer maxWaitingAfterSendingSeconds; + private Integer maxThreadPoolSize; + private Integer minThreadPoolSize; - public Integer getMaxWaitingAfterSendingSeconds() { - return maxWaitingAfterSendingSeconds; - } + public Integer getMaxWaitingAfterSendingSeconds() { + return maxWaitingAfterSendingSeconds; + } - public void setMaxWaitingAfterSendingSeconds(Integer maxWaitingAfterSendingSeconds) { - this.maxWaitingAfterSendingSeconds = maxWaitingAfterSendingSeconds; - } + public void setMaxWaitingAfterSendingSeconds(Integer maxWaitingAfterSendingSeconds) { + this.maxWaitingAfterSendingSeconds = maxWaitingAfterSendingSeconds; + } - public Integer getMaxThreadPoolSize() { - return maxThreadPoolSize; - } + public Integer getMaxThreadPoolSize() { + return maxThreadPoolSize; + } - public void setMaxThreadPoolSize(Integer maxThreadPoolSize) { - this.maxThreadPoolSize = maxThreadPoolSize; - } + public void setMaxThreadPoolSize(Integer maxThreadPoolSize) { + this.maxThreadPoolSize = maxThreadPoolSize; + } - public Integer getMinThreadPoolSize() { - return minThreadPoolSize; - } + public Integer getMinThreadPoolSize() { + return minThreadPoolSize; + } - public void setMinThreadPoolSize(Integer minThreadPoolSize) { - this.minThreadPoolSize = minThreadPoolSize; - } + public void setMinThreadPoolSize(Integer minThreadPoolSize) { + this.minThreadPoolSize = minThreadPoolSize; + } - @Override - public String toString() { - return "DistributionNotificationTopicConfig [maxWaitingAfterSendingSeconds=" + maxWaitingAfterSendingSeconds - + ", maxThreadPoolSize=" + maxThreadPoolSize + ", minThreadPoolSize=" + minThreadPoolSize + "]"; - } + @Override + public String toString() { + return "DistributionNotificationTopicConfig [maxWaitingAfterSendingSeconds=" + maxWaitingAfterSendingSeconds + + ", maxThreadPoolSize=" + maxThreadPoolSize + ", minThreadPoolSize=" + minThreadPoolSize + "]"; + } - } + } - public static class ComponentArtifactTypesConfig { + public static class ComponentArtifactTypesConfig { - private List info; - private List lifecycle; + private List info; + private List lifecycle; - public List getInfo() { - return info; - } + public List getInfo() { + return info; + } - public void setInfo(List info) { - this.info = info; - } + public void setInfo(List info) { + this.info = info; + } - public List getLifecycle() { - return lifecycle; - } + public List getLifecycle() { + return lifecycle; + } - public void setLifecycle(List lifecycle) { - this.lifecycle = lifecycle; - } + public void setLifecycle(List lifecycle) { + this.lifecycle = lifecycle; + } - @Override - public String toString() { - return "ArtifactTypesConfig [info=" + info + ", lifecycle=" + lifecycle + "]"; - } + @Override + public String toString() { + return "ArtifactTypesConfig [info=" + info + ", lifecycle=" + lifecycle + "]"; + } - } + } - public Integer getOpEnvRecoveryIntervalSec() { - return opEnvRecoveryIntervalSec; - } + public Integer getOpEnvRecoveryIntervalSec() { + return opEnvRecoveryIntervalSec; + } - public void setOpEnvRecoveryIntervalSec(Integer opEnvRecoveryIntervalSec) { - this.opEnvRecoveryIntervalSec = opEnvRecoveryIntervalSec; - } + public void setOpEnvRecoveryIntervalSec(Integer opEnvRecoveryIntervalSec) { + this.opEnvRecoveryIntervalSec = opEnvRecoveryIntervalSec; + } - public Integer getAllowedTimeBeforeStaleSec() { - return allowedTimeBeforeStaleSec; - } + public Integer getAllowedTimeBeforeStaleSec() { + return allowedTimeBeforeStaleSec; + } - public void setAllowedTimeBeforeStaleSec(Integer allowedTimeBeforeStaleSec) { - this.allowedTimeBeforeStaleSec = allowedTimeBeforeStaleSec; - } + public void setAllowedTimeBeforeStaleSec(Integer allowedTimeBeforeStaleSec) { + this.allowedTimeBeforeStaleSec = allowedTimeBeforeStaleSec; + } public ExternalServiceConfig getAaiConfig() { return aaiConfig; diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapConsumerConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapConsumerConfiguration.java index c99cbbaae3..926d21f395 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapConsumerConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapConsumerConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,284 +19,323 @@ */ package org.openecomp.sdc.be.config; - /** * Contains DMAAP Client configuration parameters */ public class DmaapConsumerConfiguration { - private boolean active; - private String hosts; - private String consumerGroup; - private String consumerId; - private Integer timeoutMs; - private Integer limit; - private Integer pollingInterval; - private String topic; - private Double latitude; - private Double longitude; - private String version; - private String serviceName; - private String environment; - private String partner; - private String routeOffer; - private String protocol; - private String contenttype; - private Boolean dme2TraceOn; - private String aftEnvironment; - private Integer aftDme2ConnectionTimeoutMs; - private Integer aftDme2RoundtripTimeoutMs; - private Integer aftDme2ReadTimeoutMs; - private String dme2preferredRouterFilePath; - private Credential credential; - private Integer timeLimitForNotificationHandleMs; - - public String getHosts() { - return hosts; - } - - public void setHosts(String hosts) { - this.hosts = hosts; - } - - public String getConsumerGroup() { - return consumerGroup; - } - - public void setConsumerGroup(String consumerGroup) { - this.consumerGroup = consumerGroup; - } - - public String getConsumerId() { - return consumerId; - } - - public void setConsumerId(String consumerId) { - this.consumerId = consumerId; - } - - public Integer getTimeoutMs() { - return timeoutMs; - } - - public void setTimeoutMs(Integer timeoutMs) { - this.timeoutMs = timeoutMs; - } - - public Integer getLimit() { - return limit; - } - - public void setLimit(Integer limit) { - this.limit = limit; - } - - public Integer getPollingInterval() { - return pollingInterval; - } - - public void setPollingInterval(Integer pollingInterval) { - this.pollingInterval = pollingInterval; - } - - public String getTopic() { - return topic; - } - - public void setTopic(String topic) { - this.topic = topic; - } - - public Double getLatitude() { - return latitude; - } - - public void setLatitude(Double latitude) { - this.latitude = latitude; - } - - public Double getLongitude() { - return longitude; - } - - public void setLongitude(Double longitude) { - this.longitude = longitude; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getServiceName() { - return serviceName; - } - - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } + private boolean active; + private String hosts; + private String consumerGroup; + private String consumerId; + private Integer timeoutMs; + private Integer limit; + private Integer pollingInterval; + private String topic; + private Double latitude; + private Double longitude; + private String version; + private String serviceName; + private String environment; + private String partner; + private String routeOffer; + private String protocol; + private String contenttype; + private Boolean dme2TraceOn; + private String aftEnvironment; + private Integer aftDme2ConnectionTimeoutMs; + private Integer aftDme2RoundtripTimeoutMs; + private Integer aftDme2ReadTimeoutMs; + private String dme2preferredRouterFilePath; + private Credential credential; + private Integer timeLimitForNotificationHandleMs; + private boolean aftDme2SslEnable; + private boolean aftDme2ClientIgnoreSslConfig; + private String aftDme2ClientKeystore; + private String aftDme2ClientKeystorePassword; + private String aftDme2ClientSslCertAlias; + + public String getHosts() { + return hosts; + } + + public void setHosts(String hosts) { + this.hosts = hosts; + } + + public String getConsumerGroup() { + return consumerGroup; + } + + public void setConsumerGroup(String consumerGroup) { + this.consumerGroup = consumerGroup; + } + + public String getConsumerId() { + return consumerId; + } + + public void setConsumerId(String consumerId) { + this.consumerId = consumerId; + } + + public Integer getTimeoutMs() { + return timeoutMs; + } + + public void setTimeoutMs(Integer timeoutMs) { + this.timeoutMs = timeoutMs; + } + + public Integer getLimit() { + return limit; + } + + public void setLimit(Integer limit) { + this.limit = limit; + } + + public Integer getPollingInterval() { + return pollingInterval; + } + + public void setPollingInterval(Integer pollingInterval) { + this.pollingInterval = pollingInterval; + } + + public String getTopic() { + return topic; + } + + public void setTopic(String topic) { + this.topic = topic; + } + + public Double getLatitude() { + return latitude; + } + + public void setLatitude(Double latitude) { + this.latitude = latitude; + } + + public Double getLongitude() { + return longitude; + } + + public void setLongitude(Double longitude) { + this.longitude = longitude; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getEnvironment() { + return environment; + } + + public void setEnvironment(String environment) { + this.environment = environment; + } + + public String getPartner() { + return partner; + } + + public void setPartner(String partner) { + this.partner = partner; + } + + public String getRouteOffer() { + return routeOffer; + } + + public void setRouteOffer(String routeOffer) { + this.routeOffer = routeOffer; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getContenttype() { + return contenttype; + } + + public void setContenttype(String contenttype) { + this.contenttype = contenttype; + } + + public Boolean isDme2TraceOn() { + return dme2TraceOn; + } + + public Boolean getDme2TraceOn() { + return dme2TraceOn; + } + + public void setDme2TraceOn(Boolean dme2TraceOn) { + this.dme2TraceOn = dme2TraceOn; + } + + public String getAftEnvironment() { + return aftEnvironment; + } + + public void setAftEnvironment(String aftEnvironment) { + this.aftEnvironment = aftEnvironment; + } - public String getEnvironment() { - return environment; - } + public Integer getAftDme2ConnectionTimeoutMs() { + return aftDme2ConnectionTimeoutMs; + } - public void setEnvironment(String environment) { - this.environment = environment; - } + public void setAftDme2ConnectionTimeoutMs(Integer aftDme2ConnectionTimeoutMs) { + this.aftDme2ConnectionTimeoutMs = aftDme2ConnectionTimeoutMs; + } - public String getPartner() { - return partner; - } + public Integer getAftDme2RoundtripTimeoutMs() { + return aftDme2RoundtripTimeoutMs; + } - public void setPartner(String partner) { - this.partner = partner; - } + public void setAftDme2RoundtripTimeoutMs(Integer aftDme2RoundtripTimeoutMs) { + this.aftDme2RoundtripTimeoutMs = aftDme2RoundtripTimeoutMs; + } - public String getRouteOffer() { - return routeOffer; - } + public Integer getAftDme2ReadTimeoutMs() { + return aftDme2ReadTimeoutMs; + } - public void setRouteOffer(String routeOffer) { - this.routeOffer = routeOffer; - } + public void setAftDme2ReadTimeoutMs(Integer aftDme2ReadTimeoutMs) { + this.aftDme2ReadTimeoutMs = aftDme2ReadTimeoutMs; + } - public String getProtocol() { - return protocol; - } + public String getDme2preferredRouterFilePath() { + return dme2preferredRouterFilePath; + } - public void setProtocol(String protocol) { - this.protocol = protocol; - } + public void setDme2preferredRouterFilePath(String dme2preferredRouterFilePath) { + this.dme2preferredRouterFilePath = dme2preferredRouterFilePath; + } - public String getContenttype() { - return contenttype; - } + public Credential getCredential() { + return credential; + } - public void setContenttype(String contenttype) { - this.contenttype = contenttype; - } + public void setCredential(Credential credential) { + this.credential = credential; + } - public Boolean isDme2TraceOn() { - return dme2TraceOn; - } + public boolean isActive() { return active; } - public Boolean getDme2TraceOn() { - return dme2TraceOn; - } + public void setActive(boolean isActive) { this.active = isActive; } - public void setDme2TraceOn(Boolean dme2TraceOn) { - this.dme2TraceOn = dme2TraceOn; - } + /** + * Contains Dmaap Client credential parameters: username and password + */ + public static class Credential{ + + private String username; + private String password; + + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + @Override + public String toString() { + return "Credential [username=" + username + ", password=" + password + "]"; + } + + } - public String getAftEnvironment() { - return aftEnvironment; - } + public Integer getTimeLimitForNotificationHandleMs() { + return timeLimitForNotificationHandleMs; + } - public void setAftEnvironment(String aftEnvironment) { - this.aftEnvironment = aftEnvironment; - } + public void setTimeLimitForNotificationHandleMs(Integer timeLimitForNotificationHandleMs) { + this.timeLimitForNotificationHandleMs = timeLimitForNotificationHandleMs; + } - public Integer getAftDme2ConnectionTimeoutMs() { - return aftDme2ConnectionTimeoutMs; + public boolean isAftDme2SslEnable() { + return aftDme2SslEnable; } - public void setAftDme2ConnectionTimeoutMs(Integer aftDme2ConnectionTimeoutMs) { - this.aftDme2ConnectionTimeoutMs = aftDme2ConnectionTimeoutMs; + public void setAftDme2SslEnable(boolean aftDme2SslEnable) { + this.aftDme2SslEnable = aftDme2SslEnable; } - public Integer getAftDme2RoundtripTimeoutMs() { - return aftDme2RoundtripTimeoutMs; + public boolean isAftDme2ClientIgnoreSslConfig() { + return aftDme2ClientIgnoreSslConfig; } - public void setAftDme2RoundtripTimeoutMs(Integer aftDme2RoundtripTimeoutMs) { - this.aftDme2RoundtripTimeoutMs = aftDme2RoundtripTimeoutMs; + public void setAftDme2ClientIgnoreSslConfig(boolean aftDme2ClientIgnoreSslConfig) { + this.aftDme2ClientIgnoreSslConfig = aftDme2ClientIgnoreSslConfig; } - public Integer getAftDme2ReadTimeoutMs() { - return aftDme2ReadTimeoutMs; + public String getAftDme2ClientKeystore() { + return aftDme2ClientKeystore; } - public void setAftDme2ReadTimeoutMs(Integer aftDme2ReadTimeoutMs) { - this.aftDme2ReadTimeoutMs = aftDme2ReadTimeoutMs; + public void setAftDme2ClientKeystore(String aftDme2ClientKeystore) { + this.aftDme2ClientKeystore = aftDme2ClientKeystore; } - public String getDme2preferredRouterFilePath() { - return dme2preferredRouterFilePath; - } - - public void setDme2preferredRouterFilePath(String dme2preferredRouterFilePath) { - this.dme2preferredRouterFilePath = dme2preferredRouterFilePath; - } - - public Credential getCredential() { - return credential; - } - - public void setCredential(Credential credential) { - this.credential = credential; - } - - public boolean isActive() { - return active; - } - - public void setActive(boolean isActive) { - this.active = isActive; - } - - /** - * Contains Dmaap Client credential parameters: username and password - */ - public static class Credential { - - private String username; - private String password; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - @Override - public String toString() { - return "Credential [username=" + username + ", password=" + password + "]"; - } - + public String getAftDme2ClientKeystorePassword() { + return aftDme2ClientKeystorePassword; } - @Override - public String toString() { - return "DmaapConsumerConfiguration [active=" + active + ", hosts=" + hosts + ", consumerGroup=" + consumerGroup + ", consumerId=" - + consumerId + ", timeoutMs=" + timeoutMs + ", limit=" + limit + ", pollingInterval=" + pollingInterval - + ", topic=" + topic + ", latitude=" + latitude + ", longitude=" + longitude + ", version=" + version - + ", serviceName=" + serviceName + ", environment=" + environment + ", partner=" + partner - + ", routeOffer=" + routeOffer + ", protocol=" + protocol + ", contenttype=" + contenttype - + ", dme2TraceOn=" + dme2TraceOn + ", aftEnvironment=" + aftEnvironment - + ", aftDme2ConnectionTimeoutMs=" + aftDme2ConnectionTimeoutMs + ", aftDme2RoundtripTimeoutMs=" - + aftDme2RoundtripTimeoutMs + ", aftDme2ReadTimeoutMs=" + aftDme2ReadTimeoutMs - + ", dme2preferredRouterFilePath=" + dme2preferredRouterFilePath - + ", timeLimitForNotificationHandleMs=" + timeLimitForNotificationHandleMs + ", credential=" + credential + "]"; + public void setAftDme2ClientKeystorePassword(String aftDme2ClientKeystorePassword) { + this.aftDme2ClientKeystorePassword = aftDme2ClientKeystorePassword; } - public Integer getTimeLimitForNotificationHandleMs() { - return timeLimitForNotificationHandleMs; + public String getAftDme2ClientSslCertAlias() { + return aftDme2ClientSslCertAlias; } - public void setTimeLimitForNotificationHandleMs(Integer timeLimitForNotificationHandleMs) { - this.timeLimitForNotificationHandleMs = timeLimitForNotificationHandleMs; + public void setAftDme2ClientSslCertAlias(String aftDme2ClientSslCertAlias) { + this.aftDme2ClientSslCertAlias = aftDme2ClientSslCertAlias; } + @Override + public String toString() { + return "DmaapConsumerConfiguration [active=" + active + ", hosts=" + hosts + ", consumerGroup=" + consumerGroup + + ", consumerId=" + consumerId + ", timeoutMs=" + timeoutMs + ", limit=" + limit + ", pollingInterval=" + + pollingInterval + ", topic=" + topic + ", latitude=" + latitude + ", longitude=" + longitude + + ", version=" + version + ", serviceName=" + serviceName + ", environment=" + environment + + ", partner=" + partner + ", routeOffer=" + routeOffer + ", protocol=" + protocol + ", contenttype=" + + contenttype + ", dme2TraceOn=" + dme2TraceOn + ", aftEnvironment=" + aftEnvironment + + ", aftDme2ConnectionTimeoutMs=" + aftDme2ConnectionTimeoutMs + ", aftDme2RoundtripTimeoutMs=" + + aftDme2RoundtripTimeoutMs + ", aftDme2ReadTimeoutMs=" + aftDme2ReadTimeoutMs + + ", dme2preferredRouterFilePath=" + dme2preferredRouterFilePath + ", credential=" + credential + + ", timeLimitForNotificationHandleMs=" + timeLimitForNotificationHandleMs + ", aftDme2SslEnable=" + + aftDme2SslEnable + ", aftDme2ClientIgnoreSslConfig=" + aftDme2ClientIgnoreSslConfig + + ", aftDme2ClientKeystore=" + aftDme2ClientKeystore + ", aftDme2ClientKeystorePassword=" + + aftDme2ClientKeystorePassword + ", aftDme2ClientSslCertAlias=" + aftDme2ClientSslCertAlias + "]"; + } + } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapProducerConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapProducerConfiguration.java new file mode 100644 index 0000000000..52d1def11f --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapProducerConfiguration.java @@ -0,0 +1,325 @@ +package org.openecomp.sdc.be.config; +/** + * Contains DMAAP Client configuration parameters + */ +public class DmaapProducerConfiguration { + + private Boolean active; + private String hosts; + private String consumerGroup; + private String consumerId; + private Integer timeoutMs; + private Integer limit; + private Integer pollingInterval; + private String topic; + private Double latitude; + private Double longitude; + private String version; + private String serviceName; + private String environment; + private String partner; + private String routeOffer; + private String protocol; + private String contenttype; + private Boolean dme2TraceOn; + private String aftEnvironment; + private Integer aftDme2ConnectionTimeoutMs; + private Integer aftDme2RoundtripTimeoutMs; + private Integer aftDme2ReadTimeoutMs; + private String dme2preferredRouterFilePath; + private Credential credential; + private Integer timeLimitForNotificationHandleMs; + private boolean aftDme2SslEnable; + private boolean aftDme2ClientIgnoreSslConfig; + private String aftDme2ClientKeystore; + private String aftDme2ClientKeystorePassword; + private String aftDme2ClientSslCertAlias; + + + public Boolean getActive() { + return active; + } + + public void setActive(Boolean active) { + this.active = active; + } + + public String getHosts() { + return hosts; + } + + public void setHosts(String hosts) { + this.hosts = hosts; + } + + public String getConsumerGroup() { + return consumerGroup; + } + + public void setConsumerGroup(String consumerGroup) { + this.consumerGroup = consumerGroup; + } + + public String getConsumerId() { + return consumerId; + } + + public void setConsumerId(String consumerId) { + this.consumerId = consumerId; + } + + public Integer getTimeoutMs() { + return timeoutMs; + } + + public void setTimeoutMs(Integer timeoutMs) { + this.timeoutMs = timeoutMs; + } + + public Integer getLimit() { + return limit; + } + + public void setLimit(Integer limit) { + this.limit = limit; + } + + public Integer getPollingInterval() { + return pollingInterval; + } + + public void setPollingInterval(Integer pollingInterval) { + this.pollingInterval = pollingInterval; + } + + public String getTopic() { + return topic; + } + + public void setTopic(String topic) { + this.topic = topic; + } + + public Double getLatitude() { + return latitude; + } + + public void setLatitude(Double latitude) { + this.latitude = latitude; + } + + public Double getLongitude() { + return longitude; + } + + public void setLongitude(Double longitude) { + this.longitude = longitude; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getEnvironment() { + return environment; + } + + public void setEnvironment(String environment) { + this.environment = environment; + } + + public String getPartner() { + return partner; + } + + public void setPartner(String partner) { + this.partner = partner; + } + + public String getRouteOffer() { + return routeOffer; + } + + public void setRouteOffer(String routeOffer) { + this.routeOffer = routeOffer; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getContenttype() { + return contenttype; + } + + public void setContenttype(String contenttype) { + this.contenttype = contenttype; + } + + public Boolean isDme2TraceOn() { + return dme2TraceOn; + } + + public Boolean getDme2TraceOn() { + return dme2TraceOn; + } + + public void setDme2TraceOn(Boolean dme2TraceOn) { + this.dme2TraceOn = dme2TraceOn; + } + + public String getAftEnvironment() { + return aftEnvironment; + } + + public void setAftEnvironment(String aftEnvironment) { + this.aftEnvironment = aftEnvironment; + } + + public Integer getAftDme2ConnectionTimeoutMs() { + return aftDme2ConnectionTimeoutMs; + } + + public void setAftDme2ConnectionTimeoutMs(Integer aftDme2ConnectionTimeoutMs) { + this.aftDme2ConnectionTimeoutMs = aftDme2ConnectionTimeoutMs; + } + + public Integer getAftDme2RoundtripTimeoutMs() { + return aftDme2RoundtripTimeoutMs; + } + + public void setAftDme2RoundtripTimeoutMs(Integer aftDme2RoundtripTimeoutMs) { + this.aftDme2RoundtripTimeoutMs = aftDme2RoundtripTimeoutMs; + } + + public Integer getAftDme2ReadTimeoutMs() { + return aftDme2ReadTimeoutMs; + } + + public void setAftDme2ReadTimeoutMs(Integer aftDme2ReadTimeoutMs) { + this.aftDme2ReadTimeoutMs = aftDme2ReadTimeoutMs; + } + + public String getDme2preferredRouterFilePath() { + return dme2preferredRouterFilePath; + } + + public void setDme2preferredRouterFilePath(String dme2preferredRouterFilePath) { + this.dme2preferredRouterFilePath = dme2preferredRouterFilePath; + } + + public Credential getCredential() { + return credential; + } + + public void setCredential(Credential credential) { + this.credential = credential; + } + + /** + * Contains Dmaap Client credential parameters: username and password + */ + public static class Credential{ + + private String username; + private String password; + + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + @Override + public String toString() { + return "Credential [username=" + username + ", password=" + password + "]"; + } + + } + public Integer getTimeLimitForNotificationHandleMs() { + return timeLimitForNotificationHandleMs; + } + + public void setTimeLimitForNotificationHandleMs(Integer timeLimitForNotificationHandleMs) { + this.timeLimitForNotificationHandleMs = timeLimitForNotificationHandleMs; + } + + public boolean isAftDme2SslEnable() { + return aftDme2SslEnable; + } + + public void setAftDme2SslEnable(boolean aftDme2SslEnable) { + this.aftDme2SslEnable = aftDme2SslEnable; + } + + public boolean isAftDme2ClientIgnoreSslConfig() { + return aftDme2ClientIgnoreSslConfig; + } + + public void setAftDme2ClientIgnoreSslConfig(boolean aftDme2ClientIgnoreSslConfig) { + this.aftDme2ClientIgnoreSslConfig = aftDme2ClientIgnoreSslConfig; + } + + public String getAftDme2ClientKeystore() { + return aftDme2ClientKeystore; + } + + public void setAftDme2ClientKeystore(String aftDme2ClientKeystore) { + this.aftDme2ClientKeystore = aftDme2ClientKeystore; + } + + public String getAftDme2ClientKeystorePassword() { + return aftDme2ClientKeystorePassword; + } + + public void setAftDme2ClientKeystorePassword(String aftDme2ClientKeystorePassword) { + this.aftDme2ClientKeystorePassword = aftDme2ClientKeystorePassword; + } + + public String getAftDme2ClientSslCertAlias() { + return aftDme2ClientSslCertAlias; + } + + public void setAftDme2ClientSslCertAlias(String aftDme2ClientSslCertAlias) { + this.aftDme2ClientSslCertAlias = aftDme2ClientSslCertAlias; + } + + @Override + public String toString() { + return "DmaapProducerConfiguration [hosts=" + hosts + ", consumerGroup=" + consumerGroup + ", consumerId=" + + consumerId + ", timeoutMs=" + timeoutMs + ", limit=" + limit + ", pollingInterval=" + pollingInterval + + ", topic=" + topic + ", latitude=" + latitude + ", longitude=" + longitude + ", version=" + version + + ", serviceName=" + serviceName + ", environment=" + environment + ", partner=" + partner + + ", routeOffer=" + routeOffer + ", protocol=" + protocol + ", contenttype=" + contenttype + + ", dme2TraceOn=" + dme2TraceOn + ", aftEnvironment=" + aftEnvironment + + ", aftDme2ConnectionTimeoutMs=" + aftDme2ConnectionTimeoutMs + ", aftDme2RoundtripTimeoutMs=" + + aftDme2RoundtripTimeoutMs + ", aftDme2ReadTimeoutMs=" + aftDme2ReadTimeoutMs + + ", dme2preferredRouterFilePath=" + dme2preferredRouterFilePath + + ", timeLimitForNotificationHandleMs=" + timeLimitForNotificationHandleMs+ ", credential=" + credential + + ", aftDme2SslEnable=" + aftDme2SslEnable + ", aftDme2ClientIgnoreSslConfig=" + aftDme2ClientIgnoreSslConfig + + ", aftDme2ClientKeystore=" + aftDme2ClientKeystore + ", aftDme2ClientSslCertAlias=" + aftDme2ClientSslCertAlias + "]"; + } + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmeConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmeConfiguration.java index 4e553fdd8d..d876378421 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmeConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmeConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,27 +21,20 @@ package org.openecomp.sdc.be.config; public class DmeConfiguration { - private String dme2Search = "DME2SEARCH"; - private String dme2Resolve = "DME2RESOLVE"; + private String lookupUriFormat = "http://DME2RESOLVE/service=%s/version=1.0.0/envContext=%s/routeOffer=DEFAULT"; - public String getDme2Search() { - return dme2Search; + public String getLookupUriFormat() { + return lookupUriFormat; } - public void setDme2Search(String dme2Search) { - this.dme2Search = dme2Search; - } - - public String getDme2Resolve() { - return dme2Resolve; - } - - public void setDme2Resolve(String dme2Resolve) { - this.dme2Resolve = dme2Resolve; + public void setLookupUriFormat(String lookupUriFormat) { + this.lookupUriFormat = lookupUriFormat; } @Override public String toString() { - return "DmeConfiguration [dme2Search=" + dme2Search + ", dme2Resolve=" + dme2Resolve + "]"; + return "DmeConfiguration{" + + "lookupUriFormat='" + lookupUriFormat + '\'' + + '}'; } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorConfiguration.java index 3b7efbabf4..52ea02cfab 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,29 +26,29 @@ import java.util.Map; public class ErrorConfiguration extends BasicConfiguration { - private Map errors; - - public Map getErrors() { - return errors; - } - - public void setErrors(Map errors) { - this.errors = errors; - } - - public ErrorInfo getErrorInfo(String key) { - ErrorInfo clone = null; - ErrorInfo other = errors.get(key); - if (other != null) { - clone = new ErrorInfo(); - clone.cloneData(other); - } - return clone; - } - - @Override - public String toString() { - return "ErrorConfiguration [errors=" + errors + "]"; - } + private Map errors; + + public Map getErrors() { + return errors; + } + + public void setErrors(Map errors) { + this.errors = errors; + } + + public ErrorInfo getErrorInfo(String key) { + ErrorInfo clone = null; + ErrorInfo other = errors.get(key); + if (other != null) { + clone = new ErrorInfo(); + clone.cloneData(other); + } + return clone; + } + + @Override + public String toString() { + return "ErrorConfiguration [errors=" + errors + "]"; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorInfo.java index 0846fc7083..ec9a61c81f 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,76 +24,76 @@ import org.openecomp.sdc.common.log.wrappers.Logger; public class ErrorInfo { - private Integer code; - private String message; - private String messageId; - private ErrorInfoType errorInfoType; - - private static final String SVC_PREFIX = "SVC"; - private static final String POL_PREFIX = "POL"; - - private static Logger log = Logger.getLogger(ErrorInfo.class.getName()); - - public ErrorInfo() { - this.errorInfoType = ErrorInfoType.OK; - } - - public Integer getCode() { - return code; - } - - public void setCode(Integer code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getMessageId() { - return messageId; - } - - public void setMessageId(String messageId) { - // Determining the type of error - if (messageId == null) { - this.errorInfoType = ErrorInfoType.OK; - } else if (messageId.startsWith(SVC_PREFIX)) { - this.errorInfoType = ErrorInfoType.SERVICE_EXCEPTION; - } else if (messageId.startsWith(POL_PREFIX)) { - this.errorInfoType = ErrorInfoType.POLICY_EXCEPTION; - } else { - // unexpected - should it fail the startup? - BeEcompErrorManager.getInstance().logErrorConfigFileFormat("Error Info", - "Could not set error info type for message id " + messageId); - log.debug("Error: unexpected error message ID {}, should start with {} or {}", messageId, SVC_PREFIX, - POL_PREFIX); - } - this.messageId = messageId; - } - - public ErrorInfoType getErrorInfoType() { - return this.errorInfoType; - } - - public void cloneData(ErrorInfo other) { - this.code = other.getCode(); - this.message = other.getMessage(); - this.messageId = other.getMessageId(); - this.errorInfoType = other.errorInfoType; - } - - @Override - public String toString() { - return "ErrorInfo [code=" + code + ", messageId=" + messageId + ", message=" + message + "]"; - } - - public enum ErrorInfoType { - OK, POLICY_EXCEPTION, SERVICE_EXCEPTION - } + private Integer code; + private String message; + private String messageId; + private ErrorInfoType errorInfoType; + + private static final String SVC_PREFIX = "SVC"; + private static final String POL_PREFIX = "POL"; + + private static Logger log = Logger.getLogger(ErrorInfo.class.getName()); + + public ErrorInfo() { + this.errorInfoType = ErrorInfoType.OK; + } + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getMessageId() { + return messageId; + } + + public void setMessageId(String messageId) { + // Determining the type of error + if (messageId == null) { + this.errorInfoType = ErrorInfoType.OK; + } else if (messageId.startsWith(SVC_PREFIX)) { + this.errorInfoType = ErrorInfoType.SERVICE_EXCEPTION; + } else if (messageId.startsWith(POL_PREFIX)) { + this.errorInfoType = ErrorInfoType.POLICY_EXCEPTION; + } else { + // unexpected - should it fail the startup? + BeEcompErrorManager.getInstance().logErrorConfigFileFormat("Error Info", + "Could not set error info type for message id " + messageId); + log.debug("Error: unexpected error message ID {}, should start with {} or {}", messageId, SVC_PREFIX, + POL_PREFIX); + } + this.messageId = messageId; + } + + public ErrorInfoType getErrorInfoType() { + return this.errorInfoType; + } + + public void cloneData(ErrorInfo other) { + this.code = other.getCode(); + this.message = other.getMessage(); + this.messageId = other.getMessageId(); + this.errorInfoType = other.errorInfoType; + } + + @Override + public String toString() { + return "ErrorInfo [code=" + code + ", messageId=" + messageId + ", message=" + message + "]"; + } + + public enum ErrorInfoType { + OK, POLICY_EXCEPTION, SERVICE_EXCEPTION + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/Neo4jErrorsConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/Neo4jErrorsConfiguration.java index 7dc8dc8f26..02965242cf 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/Neo4jErrorsConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/Neo4jErrorsConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,23 +25,23 @@ import org.openecomp.sdc.common.api.BasicConfiguration; import java.util.Map; public class Neo4jErrorsConfiguration extends BasicConfiguration { - private Map errors; + private Map errors; - public Map getErrors() { - return errors; - } + public Map getErrors() { + return errors; + } - public void setErrors(Map errors) { - this.errors = errors; - } + public void setErrors(Map errors) { + this.errors = errors; + } - public String getErrorMessage(String key) { - return errors.get(key); - } + public String getErrorMessage(String key) { + return errors.get(key); + } - @Override - public String toString() { - return "Neo4jErrorsConfiguration [errors=" + errors + "]"; - } + @Override + public String toString() { + return "Neo4jErrorsConfiguration [errors=" + errors + "]"; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/validation/DeploymentArtifactHeatConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/validation/DeploymentArtifactHeatConfiguration.java index 88bab26d7c..72b53bac75 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/validation/DeploymentArtifactHeatConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/validation/DeploymentArtifactHeatConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,33 +24,34 @@ import java.util.Map; /** * Currently for deployment artifacts HEAT validation only. - * + * * Other artifacts might require different fields validation Be sure to check it * before you re-use this class - * + * * @author paharoni + * */ public class DeploymentArtifactHeatConfiguration { - // All the rest of heat file is not needed for now... - private String heat_template_version; + // All the rest of heat file is not needed for now... + String heat_template_version; - private Map resources; + Map resources; - public String getHeat_template_version() { - return heat_template_version; - } + public String getHeat_template_version() { + return heat_template_version; + } - public void setHeat_template_version(String heat_template_version) { - this.heat_template_version = heat_template_version; - } + public void setHeat_template_version(String heat_template_version) { + this.heat_template_version = heat_template_version; + } - public Map getResources() { - return resources; - } + public Map getResources() { + return resources; + } - public void setResources(Map resources) { - this.resources = resources; - } + public void setResources(Map resources) { + this.resources = resources; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java b/common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java index 0117b2be9e..c29574dd1b 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -46,64 +46,64 @@ import java.util.concurrent.TimeUnit; public class BeMonitoringService { - private static final String URL = "%s://%s:%s/sdc2/rest/monitoring"; - private static Logger monitoringLogger = Logger.getLogger("asdc.be.monitoring.service"); - private static Logger log = Logger.getLogger(BeMonitoringService.class.getName()); - private static Gson gson = new GsonBuilder().setPrettyPrinting().create(); + private static final String URL = "%s://%s:%s/sdc2/rest/monitoring"; + private static Logger monitoringLogger = Logger.getLogger("asdc.be.monitoring.service"); + private static Logger log = Logger.getLogger(BeMonitoringService.class.getName()); + private static Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private class MonitoringScheduledTask implements Runnable { - @Override - public void run() { - monitoringLogger.trace("Executing BE Monitoring Task - Start"); - MonitoringEvent monitoringMetrics = MonitoringMetricsFetcher.getInstance().getMonitoringMetrics(); - processMonitoringEvent(monitoringMetrics); - monitoringLogger.trace("Executing BE Monitoring Task - Status = {}", monitoringMetrics.toString()); - } - } + private class MonitoringScheduledTask implements Runnable { + @Override + public void run() { + monitoringLogger.trace("Executing BE Monitoring Task - Start"); + MonitoringEvent monitoringMetrics = MonitoringMetricsFetcher.getInstance().getMonitoringMetrics(); + processMonitoringEvent(monitoringMetrics); + monitoringLogger.trace("Executing BE Monitoring Task - Status = {}", monitoringMetrics.toString()); + } + } - /** - * This executor will execute the Monitoring task. - */ - private ScheduledExecutorService monitoringExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "BE-Monitoring-Thread"); - } - }); - private ServletContext context; + /** + * This executor will execute the Monitoring task. + */ + ScheduledExecutorService monitoringExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "BE-Monitoring-Thread"); + } + }); + private ServletContext context; - public BeMonitoringService(ServletContext context) { - this.context = context; - } + public BeMonitoringService(ServletContext context) { + this.context = context; + } - public void start(int interval) { - Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) - .getConfiguration(); - if (config.getSystemMonitoring().getEnabled()) { - log.info("BE monitoring service is enabled, interval is {} seconds", interval); - this.monitoringExecutor.scheduleAtFixedRate(new MonitoringScheduledTask(), 0, interval, TimeUnit.SECONDS); - } else { - log.info("BE monitoring service is disabled"); - } - } + public void start(int interval) { + Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) + .getConfiguration(); + if (config.getSystemMonitoring().getEnabled()) { + log.info("BE monitoring service is enabled, interval is {} seconds", interval); + this.monitoringExecutor.scheduleAtFixedRate(new MonitoringScheduledTask(), 0, interval, TimeUnit.SECONDS); + } else { + log.info("BE monitoring service is disabled"); + } + } - private void processMonitoringEvent(MonitoringEvent monitoringMetrics) { - try { - Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) - .getConfiguration(); - String redirectedUrl = String.format(URL, config.getBeProtocol(), config.getBeFqdn(), - config.getBeHttpPort()); + private void processMonitoringEvent(MonitoringEvent monitoringMetrics) { + try { + Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) + .getConfiguration(); + String redirectedUrl = String.format(URL, config.getBeProtocol(), config.getBeFqdn(), + config.getBeHttpPort()); - final int timeout = 3000; - String monitoringMetricsJson = gson.toJson(monitoringMetrics); - HttpEntity myEntity = new StringEntity(monitoringMetricsJson, ContentType.APPLICATION_JSON); - HttpResponse httpResponse = HttpRequest.post(redirectedUrl, myEntity, new HttpClientConfig(new Timeouts(timeout, timeout))); + final int timeout = 3000; + String monitoringMetricsJson = gson.toJson(monitoringMetrics); + HttpEntity myEntity = new StringEntity(monitoringMetricsJson, ContentType.APPLICATION_JSON); + HttpResponse httpResponse = HttpRequest.post(redirectedUrl, myEntity, new HttpClientConfig(new Timeouts(timeout, timeout))); int beResponseStatus = httpResponse.getStatusCode(); if (beResponseStatus != HttpStatus.SC_OK) { - monitoringLogger.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Unexpected HTTP response from BE : {}", beResponseStatus); + monitoringLogger.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Unexpected HTTP response from BE : {}", beResponseStatus); } - } catch (Exception e) { - monitoringLogger.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Monitoring BE failed with exception ", e); - } - } + } catch (Exception e) { + monitoringLogger.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Monitoring BE failed with exception ", e); + } + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ApplicationErrorCodesEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ApplicationErrorCodesEnum.java index 2127441cb7..fa0f30842b 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ApplicationErrorCodesEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ApplicationErrorCodesEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,16 +22,16 @@ package org.openecomp.sdc.common.api; public enum ApplicationErrorCodesEnum { - POL5000, // INTERNAL_ERROR + POL5000, // INTERNAL_ERROR - SVC4000, // INVALID_INPUT + SVC4000, // INVALID_INPUT - SVC4002, // MISSING_INFORMATION - SVC4003, // RESOURCE_NAME_ALREADY_EXIST - SVC4004, // MISSING_CATEGORY - SVC4005, // MISSING_TAGS - SVC4006, // MISSING_DESCRIPTION - SVC4007, // BAD_CATEGORY + SVC4002, // MISSING_INFORMATION + SVC4003, // RESOURCE_NAME_ALREADY_EXIST + SVC4004, // MISSING_CATEGORY + SVC4005, // MISSING_TAGS + SVC4006, // MISSING_DESCRIPTION + SVC4007, // BAD_CATEGORY - SVC4030; // RESTRICTED_ACTION + SVC4030; // RESTRICTED_ACTION } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactGroupTypeEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactGroupTypeEnum.java index d3107e0117..c990d43f64 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactGroupTypeEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactGroupTypeEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,37 +25,37 @@ import java.util.List; public enum ArtifactGroupTypeEnum { - INFORMATIONAL("INFORMATIONAL"), DEPLOYMENT("DEPLOYMENT"), LIFE_CYCLE("LIFE_CYCLE"), SERVICE_API("SERVICE_API"), TOSCA("TOSCA"), OTHER("OTHER"); - - private String type; - - ArtifactGroupTypeEnum(String type) { - this.type = type; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public static ArtifactGroupTypeEnum findType(final String type) { - for (ArtifactGroupTypeEnum ate : ArtifactGroupTypeEnum.values()) { - if (ate.getType().equals(type)) { - return ate; - } - } - return null; - } - - public static List getAllTypes() { - List types = new ArrayList<>(); - for (ArtifactGroupTypeEnum ate : ArtifactGroupTypeEnum.values()) { - types.add(ate.getType()); - } - return types; - } + INFORMATIONAL("INFORMATIONAL"), DEPLOYMENT("DEPLOYMENT"), LIFE_CYCLE("LIFE_CYCLE"), SERVICE_API("SERVICE_API"), TOSCA("TOSCA"), OTHER("OTHER"); + + private String type; + + ArtifactGroupTypeEnum(String type) { + this.type = type; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public static ArtifactGroupTypeEnum findType(final String type) { + for (ArtifactGroupTypeEnum ate : ArtifactGroupTypeEnum.values()) { + if (ate.getType().equals(type)) { + return ate; + } + } + return null; + } + + public static List getAllTypes() { + List types = new ArrayList<>(); + for (ArtifactGroupTypeEnum ate : ArtifactGroupTypeEnum.values()) { + types.add(ate.getType()); + } + return types; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactTypeEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactTypeEnum.java index 722a3e74cc..9d0ff1c083 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactTypeEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactTypeEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,41 +27,43 @@ import lombok.Getter; /** * Enum That Represents possible Artifacts Types. + * */ @Getter @AllArgsConstructor public enum ArtifactTypeEnum { - CHEF("CHEF"), PUPPET("PUPPET"), YANG("YANG"), SHELL_SCRIPT("SHELL_SCRIPT"), SHELL("SHELL"), ICON("ICON"), UNKNOWN("UNKNOWN"), HEAT("HEAT"), DG_XML("DG_XML"), MURANO_PKG("MURANO_PKG"), HEAT_ENV("HEAT_ENV"), YANG_XML("YANG_XML"), HEAT_VOL("HEAT_VOL"), - HEAT_NET("HEAT_NET"), OTHER("OTHER"), WORKFLOW("WORKFLOW"), NETWORK_CALL_FLOW("NETWORK_CALL_FLOW"), TOSCA_TEMPLATE("TOSCA_TEMPLATE"), TOSCA_CSAR("TOSCA_CSAR"), VNF_CATALOG("VNF_CATALOG"), VF_LICENSE("VF_LICENSE"), BPEL("BPEL"), - VENDOR_LICENSE("VENDOR_LICENSE"), MODEL_INVENTORY_PROFILE("MODEL_INVENTORY_PROFILE"), MODEL_QUERY_SPEC("MODEL_QUERY_SPEC"), APPC_CONFIG("APPC_CONFIG"), HEAT_NESTED("HEAT_NESTED"), HEAT_ARTIFACT("HEAT_ARTIFACT"), CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT("CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT"), - VF_MODULES_METADATA("VF_MODULES_METADATA"), LIFECYCLE_OPERATIONS("LIFECYCLE_OPERATIONS"), VES_EVENTS("VES_EVENTS"), PERFORMANCE_COUNTER("PERFORMANCE_COUNTER"), UCPE_LAYER_2_CONFIGURATION("UCPE_LAYER_2_CONFIGURATION"), - CONTROLLER_BLUEPRINT_ARCHIVE("CONTROLLER_BLUEPRINT_ARCHIVE"), - // DCAE Artifacts - DCAE_TOSCA("DCAE_TOSCA"), DCAE_JSON("DCAE_JSON"), DCAE_POLICY("DCAE_POLICY"), DCAE_DOC("DCAE_DOC"), DCAE_EVENT("DCAE_EVENT"), DCAE_INVENTORY_TOSCA("DCAE_INVENTORY_TOSCA"), DCAE_INVENTORY_JSON("DCAE_INVENTORY_JSON"), - DCAE_INVENTORY_POLICY("DCAE_INVENTORY_POLICY"), DCAE_INVENTORY_DOC("DCAE_INVENTORY_DOC"), DCAE_INVENTORY_BLUEPRINT("DCAE_INVENTORY_BLUEPRINT"), DCAE_INVENTORY_EVENT("DCAE_INVENTORY_EVENT"), - // AAI Artifacts - AAI_SERVICE_MODEL("AAI_SERVICE_MODEL"), AAI_VF_MODEL("AAI_VF_MODEL"), AAI_VF_MODULE_MODEL("AAI_VF_MODULE_MODEL"), AAI_VF_INSTANCE_MODEL("AAI_VF_INSTANCE_MODEL"), - // MIB artifacts - SNMP_POLL("SNMP_POLL"), SNMP_TRAP("SNMP_TRAP"), GUIDE("GUIDE"), - PLAN("PLAN"), PM_DICTIONARY("PM_DICTIONARY"), YANG_MODULE("YANG_MODULE"), + CHEF("CHEF"), PUPPET("PUPPET"), YANG("YANG"), SHELL_SCRIPT("SHELL_SCRIPT"), SHELL("SHELL"), ICON("ICON"), UNKNOWN("UNKNOWN"), HEAT("HEAT"), DG_XML("DG_XML"), MURANO_PKG("MURANO_PKG"), HEAT_ENV("HEAT_ENV"), YANG_XML("YANG_XML"), HEAT_VOL("HEAT_VOL"), + HEAT_NET("HEAT_NET"), OTHER("OTHER"), WORKFLOW("WORKFLOW"), NETWORK_CALL_FLOW("NETWORK_CALL_FLOW"), TOSCA_TEMPLATE("TOSCA_TEMPLATE"), TOSCA_CSAR("TOSCA_CSAR"), VNF_CATALOG("VNF_CATALOG"), VF_LICENSE("VF_LICENSE"), BPEL("BPEL"), + VENDOR_LICENSE("VENDOR_LICENSE"), MODEL_INVENTORY_PROFILE("MODEL_INVENTORY_PROFILE"), MODEL_QUERY_SPEC("MODEL_QUERY_SPEC"), APPC_CONFIG("APPC_CONFIG"), HEAT_NESTED("HEAT_NESTED"), HEAT_ARTIFACT("HEAT_ARTIFACT"), CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT("CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT"), + VF_MODULES_METADATA("VF_MODULES_METADATA"), LIFECYCLE_OPERATIONS("LIFECYCLE_OPERATIONS"), VES_EVENTS("VES_EVENTS"), PERFORMANCE_COUNTER("PERFORMANCE_COUNTER"),UCPE_LAYER_2_CONFIGURATION("UCPE_LAYER_2_CONFIGURATION"), + CONTROLLER_BLUEPRINT_ARCHIVE("CONTROLLER_BLUEPRINT_ARCHIVE"), + // DCAE Artifacts + DCAE_TOSCA("DCAE_TOSCA"), DCAE_JSON("DCAE_JSON"), DCAE_POLICY("DCAE_POLICY"), DCAE_DOC("DCAE_DOC"), DCAE_EVENT("DCAE_EVENT"), DCAE_INVENTORY_TOSCA("DCAE_INVENTORY_TOSCA"), DCAE_INVENTORY_JSON("DCAE_INVENTORY_JSON"), + DCAE_INVENTORY_POLICY("DCAE_INVENTORY_POLICY"), DCAE_INVENTORY_DOC("DCAE_INVENTORY_DOC"), DCAE_INVENTORY_BLUEPRINT("DCAE_INVENTORY_BLUEPRINT"), DCAE_INVENTORY_EVENT("DCAE_INVENTORY_EVENT"), + // AAI Artifacts + AAI_SERVICE_MODEL("AAI_SERVICE_MODEL"), AAI_VF_MODEL("AAI_VF_MODEL"), AAI_VF_MODULE_MODEL("AAI_VF_MODULE_MODEL"), AAI_VF_INSTANCE_MODEL("AAI_VF_INSTANCE_MODEL"), + // MIB artifacts + SNMP_POLL ("SNMP_POLL"), SNMP_TRAP("SNMP_TRAP"), GUIDE("GUIDE"), + PLAN("PLAN"), PM_DICTIONARY("PM_DICTIONARY"), YANG_MODULE("YANG_MODULE"), ANSIBLE_PLAYBOOK("ANSIBLE_PLAYBOOK"), ONBOARDED_PACKAGE("ONBOARDED_PACKAGE"), PNF_SW_INFORMATION("PNF_SW_INFORMATION"); private final String type; - public static ArtifactTypeEnum findType(final String type) { + + public static ArtifactTypeEnum findType(final String type) { for (final ArtifactTypeEnum ate : ArtifactTypeEnum.values()) { - if (ate.getType().equalsIgnoreCase(type)) { - return ate; - } - } - return null; - } + if (ate.getType().equalsIgnoreCase(type)) { + return ate; + } + } + return null; + } - public static List getAllTypes() { + public static List getAllTypes() { final List types = new ArrayList<>(); for (final ArtifactTypeEnum ate : ArtifactTypeEnum.values()) { - types.add(ate.getType()); - } - return types; - } + types.add(ate.getType()); + } + return types; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/BasicConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/BasicConfiguration.java index 271fbb7a96..5152b2af26 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/BasicConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/BasicConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ConfigurationListener.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ConfigurationListener.java index 360562b91a..d60ed6dabc 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ConfigurationListener.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ConfigurationListener.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,29 +22,29 @@ package org.openecomp.sdc.common.api; public class ConfigurationListener { - private Class type; - private FileChangeCallback callBack; + private Class type; + private FileChangeCallback callBack; - public ConfigurationListener(Class type, FileChangeCallback callBack) { - super(); - this.type = type; - this.callBack = callBack; - } + public ConfigurationListener(Class type, FileChangeCallback callBack) { + super(); + this.type = type; + this.callBack = callBack; + } - public Class getType() { - return type; - } + public Class getType() { + return type; + } - public void setType(Class type) { - this.type = type; - } + public void setType(Class type) { + this.type = type; + } - public FileChangeCallback getCallBack() { - return callBack; - } + public FileChangeCallback getCallBack() { + return callBack; + } - public void setCallBack(FileChangeCallback callBack) { - this.callBack = callBack; - } + public void setCallBack(FileChangeCallback callBack) { + this.callBack = callBack; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ConfigurationSource.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ConfigurationSource.java index a3d4179a41..5901d1e267 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ConfigurationSource.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ConfigurationSource.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,7 +22,7 @@ package org.openecomp.sdc.common.api; public interface ConfigurationSource { - T getAndWatchConfiguration(Class className, ConfigurationListener configurationListener); + public T getAndWatchConfiguration(Class className, ConfigurationListener configurationListener); - void addWatchConfiguration(Class className, ConfigurationListener configurationListener); + public void addWatchConfiguration(Class className, ConfigurationListener configurationListener); } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java index 0ced7ec648..d11cc02d86 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,130 +22,138 @@ package org.openecomp.sdc.common.api; public final class Constants { - public static final String APPLICATION_NAME = "application-name"; - public static final String APPLICATION_VERSION = "application-version"; - public static final String CONFIG_HOME = "config.home"; - public static final String LOG_HOME = "log.home"; - public static final String YAML_SUFFIX = ".yaml"; - public static final String CONFIGURATION_SOURCE_ATTR = "configuration-source"; - public static final String MDC_APP_NAME = "APP_NAME"; - public static final String CONFIGURATION_MANAGER_ATTR = "configuration-manager"; - public static final String HEALTH_CHECK_SERVICE_ATTR = "healthCheckService"; - public static final String REST_CLIENT_ATTR = "rest-client"; - public static final String ARTIFACT_DAO_ATTR = "artifact-dao"; - public static final String UPLOAD_VALIDATORR_ATTR = "upload-validator"; - public static final String THREAD_EXECUTOR_ATTR = "thread-executor"; - public static final String ERROR_LOG_FORMAT = "EVENT = ARTIFACT_UPLOAD USER_ID=%s USER_NAME=%s ACCESS_IP=%s ACCESS_TYPE=%s RURL=%s SC=%d"; - public static final String FIRST_NAME_HEADER = "HTTP_CSP_FIRSTNAME"; - public static final String LAST_NAME_HEADER = "HTTP_CSP_LASTNAME"; - public static final String USER_ID_HEADER = "USER_ID"; - public static final String MD5_HEADER = "Content-MD5"; - public static final String CONTENT_LENGTH_HEADER = "Content-Length"; - public static final String CONTENT_DISPOSITION_HEADER = "Content-Disposition"; - public static final String CONTENT_TYPE_HEADER = "Content-Type"; - public static final String ORIGIN_HEADER = "HTTP_IV_REMOTE_ADDRESS"; - public static final String ACCESS_HEADER = "HTTP_CSP_WSTYPE"; - public static final String X_ECOMP_REQUEST_ID_HEADER = "X-ECOMP-RequestID"; - public static final String X_ECOMP_INSTANCE_ID_HEADER = "X-ECOMP-InstanceID"; - public static final String X_ECOMP_SERVICE_ID_HEADER = "X-ECOMP-ServiceID"; - public static final String X_TRANSACTION_ID_HEADER = "X-TransactionId"; - public static final String X_FROM_APP_ID = "X-FromAppId"; - public static final String HTTP = "http"; - public static final String HTTPS = "https"; - public static final String HTTP_IV_USER = "HTTP_IV_USER"; - public static final String A4C_CSAR_CONTEXT = "/rest/csars/"; - public static final String WEB_APPLICATION_CONTEXT_WRAPPER_ATTR = "web-application-context-wrapper"; - public static final String CATALOG_BE = "catalog-be"; - public static final String RESOURCE_SUPPORTED_VERSION = "0.0.1"; - public static final String ARTIFACT_ID_FORMAT = "%s:%s:%s"; // resourceName:resourceVersion:artifactName - public static final String SERVICE_ARTIFACT_ID_FORMAT = "%s:%s:%s:%s"; // serviceName:serviceVersion:nodeTemplateName:artifactName - public static final String CONTENT_DISPOSITION = "content-disposition"; - public static final String DOWNLOAD_ARTIFACT_LOGIC_ATTR = "downloadArtifactLogic"; - public static final String ASDC_RELEASE_VERSION_ATTR = "SDC-Version"; - public static final String YEAR = "year"; - public static final String MONTH = "month"; - public static final String DAY = "day"; - public static final String HOUR = "hour"; - public static final String MINUTE = "minute"; - public static final String NONE = "none"; - public static final String RESOURCE_OPERATION_MANAGER = "resourceOperationManager"; - public static final String PROPERTY_OPERATION_MANAGER = "propertyOperationManager"; - public static final String SERVICE_OPERATION_MANAGER = "serviceOperationManager"; - public static final String EMPTY_STRING = ""; - public static final String NULL_STRING = "null"; - public static final String DOUBLE_NULL_STRING = "null null"; - public static final String ECOMP_ERROR_MNGR_ATTR = "ecompErrorMngrAttr"; - public static final String AUTHORIZATION_HEADER = "Authorization"; - public static final String ACCEPT_HEADER = "Accept"; - public static final String STANDARD_INTERFACE_TYPE = "standard"; - public static final String MURANO_PKG_ARTIFACT_TYPE = "MURANO-PKG"; + public static final String APPLICATION_NAME = "application-name"; + public static final String APPLICATION_VERSION = "application-version"; + public static final String CONFIG_HOME = "config.home"; + public static final String LOG_HOME = "log.home"; + public static final String YAML_SUFFIX = ".yaml"; + public static final String CONFIGURATION_SOURCE_ATTR = "configuration-source"; + public static final String MDC_APP_NAME = "APP_NAME"; + public static final String CONFIGURATION_MANAGER_ATTR = "configuration-manager"; + public static final String HEALTH_CHECK_SERVICE_ATTR = "healthCheckService"; + public static final String REST_CLIENT_ATTR = "rest-client"; + public static final String ARTIFACT_DAO_ATTR = "artifact-dao"; + public static final String UPLOAD_VALIDATORR_ATTR = "upload-validator"; + public static final String THREAD_EXECUTOR_ATTR = "thread-executor"; + public static final String ERROR_LOG_FORMAT = "EVENT = ARTIFACT_UPLOAD USER_ID=%s USER_NAME=%s ACCESS_IP=%s ACCESS_TYPE=%s RURL=%s SC=%d"; + public static final String FIRST_NAME_HEADER = "HTTP_CSP_FIRSTNAME"; + public static final String LAST_NAME_HEADER = "HTTP_CSP_LASTNAME"; + public static final String USER_ID_HEADER = "USER_ID"; + public static final String MD5_HEADER = "Content-MD5"; + public static final String USER_AGENT_HEADER = "User-Agent"; + public static final String CONTENT_LENGTH_HEADER = "Content-Length"; + public static final String CONTENT_DISPOSITION_HEADER = "Content-Disposition"; + public static final String CONTENT_TYPE_HEADER = "Content-Type"; + public static final String ORIGIN_HEADER = "HTTP_IV_REMOTE_ADDRESS"; + public static final String ACCESS_HEADER = "HTTP_CSP_WSTYPE"; + public static final String X_ECOMP_REQUEST_ID_HEADER = "X-ECOMP-RequestID"; + public static final String X_ECOMP_INSTANCE_ID_HEADER = "X-ECOMP-InstanceID"; + public static final String X_ECOMP_SERVICE_ID_HEADER = "X-ECOMP-ServiceID"; + public static final String X_REQUEST_ID = "X-RequestID"; + public static final String X_TRANSACTION_ID_HEADER = "X-TransactionId"; + public static final String X_FROM_APP_ID = "X-FromAppId"; + public static final String PartnerName_Unknown = "UNKNOWN"; + public static final String X_InvocationID = "X-InvocationID"; + public static final String HTTP = "http"; + public static final String HTTPS = "https"; + public static final String HTTP_IV_USER = "HTTP_IV_USER"; + public static final String A4C_CSAR_CONTEXT = "/rest/csars/"; + public static final String WEB_APPLICATION_CONTEXT_WRAPPER_ATTR = "web-application-context-wrapper"; + public static final String CATALOG_BE = "catalog-be"; + public static final String RESOURCE_SUPPORTED_VERSION = "0.0.1"; + public static final String ARTIFACT_ID_FORMAT = "%s:%s:%s"; // resourceName:resourceVersion:artifactName + public static final String SERVICE_ARTIFACT_ID_FORMAT = "%s:%s:%s:%s"; // serviceName:serviceVersion:nodeTemplateName:artifactName + public static final String CONTENT_DISPOSITION = "content-disposition"; + public static final String DOWNLOAD_ARTIFACT_LOGIC_ATTR = "downloadArtifactLogic"; + public static final String ASDC_RELEASE_VERSION_ATTR = "SDC-Version"; + public static final String YEAR = "year"; + public static final String MONTH = "month"; + public static final String DAY = "day"; + public static final String HOUR = "hour"; + public static final String MINUTE = "minute"; + public static final String NONE = "none"; + public static final String RESOURCE_OPERATION_MANAGER = "resourceOperationManager"; + public static final String PROPERTY_OPERATION_MANAGER = "propertyOperationManager"; + public static final String SERVICE_OPERATION_MANAGER = "serviceOperationManager"; + public static final String EMPTY_STRING = ""; + public static final String NULL_STRING = "null"; + public static final String DOUBLE_NULL_STRING = "null null"; + public static final String ECOMP_ERROR_MNGR_ATTR = "ecompErrorMngrAttr"; + public static final String AUTHORIZATION_HEADER = "Authorization"; + public static final String ACCEPT_HEADER = "Accept"; + public static final String STANDARD_INTERFACE_TYPE = "standard"; + public static final String MURANO_PKG_ARTIFACT_TYPE = "MURANO-PKG"; - // TOSCA - public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta"; - public static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions"; - public static final String USER_DEFINED_RESOURCE_NAMESPACE_PREFIX = "org.openecomp.resource."; + // TOSCA + public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta"; + public static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions"; + public static final String USER_DEFINED_RESOURCE_NAMESPACE_PREFIX = "org.openecomp.resource."; - public static final String IS_BASE = "isBase"; - public static final String HEAT_FILE_PROPS = "heat_file"; - public static final String GROUP_POLICY_NAME_DELIMETER = ".."; - public static final String POLICY_UID_POSTFIX = ".policy"; - public static final String MODULE_NAME_FORMAT = "%s..%s..module-%s"; - public static final String MODULE_DESC_PATTERN = "[\\_\\-\\.a-zA-Z0-9]+"; - public static final String MODULE_OLD_NAME_PATTERN = "([\\w\\_\\-\\.\\s]+)(::module-)(\\d+)"; - public static final String MODULE_NEW_NAME_PATTERN = "([\\w\\_\\-\\.\\s]+\\.\\.)([\\_\\-\\.a-zA-Z0-9]+)(..module-)(\\d+)"; - public static final String MODULE_NAME_DELIMITER = "module-"; - public static final String IMPORT_STRUCTURE = "importStructure"; - public static final String DEFAULT_GROUP_VF_MODULE = "org.openecomp.groups.VfModule"; - public static final String GROUP_TOSCA_HEAT = "org.openecomp.groups.heat.HeatStack"; + public static final String IS_BASE = "isBase"; + public static final String HEAT_FILE_PROPS = "heat_file"; + public static final String GROUP_POLICY_NAME_DELIMETER = ".."; + public static final String POLICY_UID_POSTFIX = ".policy"; + public static final String MODULE_NAME_FORMAT = "%s..%s..module-%s"; + public static final String MODULE_DESC_PATTERN = "[\\_\\-\\.a-zA-Z0-9]+"; + public static final String MODULE_OLD_NAME_PATTERN = "([\\w\\_\\-\\.\\s]+)(::module-)(\\d+)"; + public static final String MODULE_NEW_NAME_PATTERN = "([\\w\\_\\-\\.\\s]+\\.\\.)([\\_\\-\\.a-zA-Z0-9]+)(..module-)(\\d+)"; + public static final String MODULE_NAME_DELIMITER = "module-"; + public static final String IMPORT_STRUCTURE = "importStructure"; + public static final String DEFAULT_GROUP_VF_MODULE = "org.openecomp.groups.VfModule"; + public static final String GROUP_TOSCA_HEAT = "org.openecomp.groups.heat.HeatStack"; - public static final String ARTIFACT_GROUP_TYPE = "artifactGroupType"; - public static final String ARTIFACT_LABEL = "artifactLabel"; - public static final String ARTIFACT_PAYLOAD_DATA = "payloadData"; - public static final String ARTIFACT_DISPLAY_NAME = "artifactDisplayName"; - public static final String ARTIFACT_DESCRIPTION = "description"; - public static final String ARTIFACT_TYPE = "artifactType"; - public static final String ARTIFACT_NAME = "artifactName"; - public static final String IS_FROM_CSAR = "isFromCsar"; - public static final String ARTIFACT_ID = "uniqueId"; - public static final String REQUIRED_ARTIFACTS = "requiredArtifacts"; - public static final String ARTIFACT_HEAT_PARAMS = "heatParameters"; - public static final String ARTIFACT_ES_ID = "esId"; + public static final String ARTIFACT_GROUP_TYPE = "artifactGroupType"; + public static final String ARTIFACT_LABEL = "artifactLabel"; + public static final String ARTIFACT_PAYLOAD_DATA = "payloadData"; + public static final String ARTIFACT_DISPLAY_NAME = "artifactDisplayName"; + public static final String ARTIFACT_DESCRIPTION = "description"; + public static final String ARTIFACT_TYPE = "artifactType"; + public static final String ARTIFACT_NAME = "artifactName"; + public static final String IS_FROM_CSAR = "isFromCsar"; + public static final String ARTIFACT_ID = "uniqueId"; + public static final String REQUIRED_ARTIFACTS = "requiredArtifacts"; + public static final String ARTIFACT_HEAT_PARAMS = "heatParameters"; + public static final String ARTIFACT_ES_ID = "esId"; + public static final String ARTIFACT_TIMEOUT = "timeout"; - public static final String ABSTRACT = "abstract"; - public static final String GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE = "Definitions/GlobalSubstitutionTypesServiceTemplate.yaml"; - public static final String ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE = "Definitions/AbstractSubstituteGlobalTypesServiceTemplate.yaml"; + public static final String ABSTRACT = "abstract"; + public static final String GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE = "Definitions/GlobalSubstitutionTypesServiceTemplate.yaml"; + public static final String ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE = "Definitions/AbstractSubstituteGlobalTypesServiceTemplate.yaml"; - public static final String VENDOR_LICENSE_MODEL = "vendor-license-model.xml"; - public static final String VENDOR_LICENSE_LABEL = "vendorlicense"; - public static final String VENDOR_LICENSE_DISPLAY_NAME = "Vendor License"; - public static final String VENDOR_LICENSE_DESCRIPTION = " Vendor license file"; + public static final String VENDOR_LICENSE_MODEL = "vendor-license-model.xml"; + public static final String VENDOR_LICENSE_LABEL = "vendorlicense"; + public static final String VENDOR_LICENSE_DISPLAY_NAME = "Vendor License"; + public static final String VENDOR_LICENSE_DESCRIPTION = " Vendor license file"; - public static final String VF_LICENSE_MODEL = "vf-license-model.xml"; - public static final String VF_LICENSE_LABEL = "vflicense"; - public static final String VF_LICENSE_DISPLAY_NAME = "VF License"; - public static final String VF_LICENSE_DESCRIPTION = "VF license file"; - public static final String GET_INPUT = "get_input"; - public static final String GET_POLICY = "get_policy"; - public static final String SERVICE_TEMPLATE_FILE_POSTFIX = "ServiceTemplate.yaml"; - public static final String SERVICE_TEMPLATES_CONTAINING_FOLDER = "Definitions/"; - public static final String UNBOUNDED = "unbounded"; + public static final String VF_LICENSE_MODEL = "vf-license-model.xml"; + public static final String VF_LICENSE_LABEL = "vflicense"; + public static final String VF_LICENSE_DISPLAY_NAME = "VF License"; + public static final String VF_LICENSE_DESCRIPTION = "VF license file"; + public static final String GET_INPUT = "get_input"; + public static final String GET_POLICY = "get_policy"; + public static final String SERVICE_TEMPLATE_FILE_POSTFIX = "ServiceTemplate.yaml"; + public static final String SERVICE_TEMPLATES_CONTAINING_FOLDER = "Definitions/"; + public static final String UNBOUNDED = "unbounded"; + + //SDC HealthCheck components + public static final String HC_COMPONENT_FE = "FE"; + public static final String HC_COMPONENT_BE = "BE"; + public static final String HC_COMPONENT_CADI = "External API"; + public static final String HC_COMPONENT_JANUSGRAPH = "JANUSGRAPH"; + public static final String HC_COMPONENT_CASSANDRA = "CASSANDRA"; + public static final String HC_COMPONENT_DISTRIBUTION_ENGINE = "DE"; + public static final String HC_COMPONENT_DMAAP_ENGINE = "DMAAP"; + public static final String HC_COMPONENT_DMAAP_PRODUCER = "DMAAP_PRODUCER"; + public static final String HC_COMPONENT_CATALOG_FACADE_MS = "CATALOG_FACADE_MS"; - //SDC HealthCheck components - public static final String HC_COMPONENT_FE = "FE"; - public static final String HC_COMPONENT_BE = "BE"; - public static final String HC_COMPONENT_JANUSGRAPH = "JANUSGRAPH"; - public static final String HC_COMPONENT_ES = "ES"; - public static final String HC_COMPONENT_CASSANDRA = "CASSANDRA"; - public static final String HC_COMPONENT_DISTRIBUTION_ENGINE = "DE"; - public static final String HC_COMPONENT_DMAAP_ENGINE = "DMAAP"; + //external HealthCheck components + public static final String HC_COMPONENT_ON_BOARDING = "ON_BOARDING"; + public static final String HC_COMPONENT_DCAE = "DCAE"; + public static final String HC_COMPONENT_ECOMP_PORTAL = "PORTAL"; - //external HealthCheck components - public static final String HC_COMPONENT_ON_BOARDING = "ON_BOARDING"; - public static final String HC_COMPONENT_DCAE = "DCAE"; - - //Plugin BL - public static final String PLUGIN_BL_COMPONENT = "pluginStatusBL"; - - private Constants() { - } + + //Plugin BL + public static final String PLUGIN_BL_COMPONENT = "pluginStatusBL"; + + private Constants(){} } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/FileChangeCallback.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/FileChangeCallback.java index 730d7067c2..5c4d3d5926 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/FileChangeCallback.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/FileChangeCallback.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,6 +22,6 @@ package org.openecomp.sdc.common.api; public interface FileChangeCallback { - void reconfigure(BasicConfiguration obj); + public void reconfigure(BasicConfiguration obj); } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/FilterDecisionEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/FilterDecisionEnum.java new file mode 100644 index 0000000000..2e0ce9481a --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/FilterDecisionEnum.java @@ -0,0 +1,6 @@ +package org.openecomp.sdc.common.api; + +public enum FilterDecisionEnum { + EXTERNAL,INTERNAL,NA; + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java index bfcba41faa..53cb6654ba 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,88 +27,96 @@ import java.lang.reflect.Type; import java.util.List; public class HealthCheckInfo { + + private String healthCheckComponent; + private HealthCheckStatus healthCheckStatus; + private String version; + private String description; + private List componentsInfo; + + public void setHealthCheckComponent(String healthCheckComponent) { + this.healthCheckComponent = healthCheckComponent; + } + + public HealthCheckInfo(String healthCheckComponent, HealthCheckStatus healthCheckStatus, + String version, String description) { + super(); + this.healthCheckComponent = healthCheckComponent; + this.healthCheckStatus = healthCheckStatus; + this.version = version; + this.description = description; + } + + public HealthCheckInfo(String healthCheckComponent, HealthCheckStatus healthCheckStatus, + String version, String description, List componentsInfo) { + super(); + this.healthCheckComponent = healthCheckComponent; + this.healthCheckStatus = healthCheckStatus; + this.version = version; + this.description = description; + this.componentsInfo = componentsInfo; +} - private String healthCheckComponent; - private HealthCheckStatus healthCheckStatus; - private String version; - private String description; - private List componentsInfo; - - public HealthCheckInfo(String healthCheckComponent, HealthCheckStatus healthCheckStatus, - String version, String description) { - super(); - this.healthCheckComponent = healthCheckComponent; - this.healthCheckStatus = healthCheckStatus; - this.version = version; - this.description = description; - } - - public HealthCheckInfo(String healthCheckComponent, HealthCheckStatus healthCheckStatus, - String version, String description, List componentsInfo) { - super(); - this.healthCheckComponent = healthCheckComponent; - this.healthCheckStatus = healthCheckStatus; - this.version = version; - this.description = description; - this.componentsInfo = componentsInfo; - } - - public HealthCheckInfo() { - super(); - } - - public String getHealthCheckComponent() { - return healthCheckComponent; - } - - public HealthCheckStatus getHealthCheckStatus() { - return healthCheckStatus; - } - - public void setHealthCheckStatus(HealthCheckStatus healthCheckStatus) { - this.healthCheckStatus = healthCheckStatus; - } - - public List getComponentsInfo() { - return componentsInfo; - } - - public void setComponentsInfo(List componentsInfo) { - this.componentsInfo = componentsInfo; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public enum HealthCheckStatus { - UP, DOWN, UNKNOWN; - } - - @Override - public String toString() { - return "HealthCheckInfo [healthCheckComponent=" + healthCheckComponent + ", healthCheckStatus=" - + healthCheckStatus + ", version=" + version + ", description=" + description + ", componentsInfo=" - + componentsInfo + "]"; - } - - public static void main(String[] args) { - String des = "[{healthCheckComponent=BE4, healthCheckStatus=UP, version=0.0.1-SNAPSHOT, description=OK}, {healthCheckComponent=BE, healthCheckStatus=UP, version=1710.0.0-SNAPSHOT, description=OK}, {healthCheckComponent=BE5, healthCheckStatus=UP, version=2.1.9, description=OK}]"; - Type listType = new TypeToken>() { - }.getType(); - List componentsInfo = new Gson().fromJson(des.toString(), listType); - System.out.println(componentsInfo.toString()); - } + public HealthCheckInfo() { + super(); + } + + public String getHealthCheckComponent() { + return healthCheckComponent; + } + + public HealthCheckStatus getHealthCheckStatus() { + return healthCheckStatus; + } + + public void setHealthCheckStatus(HealthCheckStatus healthCheckStatus) { + this.healthCheckStatus = healthCheckStatus; + } + + public List getComponentsInfo() { + return componentsInfo; + } + + public void setComponentsInfo(List componentsInfo) { + this.componentsInfo = componentsInfo; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + /*public enum HealthCheckComponent { + FE, BE, JANUSGRAPH, DE, ON_BOARDING, CASSANDRA, DCAE, + CAS, ZU;//Amdocs components + }*/ + + public enum HealthCheckStatus { + UP, DOWN, UNKNOWN; + } + + @Override + public String toString() { + return "HealthCheckInfo [healthCheckComponent=" + healthCheckComponent + ", healthCheckStatus=" + + healthCheckStatus + ", version=" + version + ", description=" + description + ", componentsInfo=" + + componentsInfo + "]"; + } + + public static void main(String[] args) { + String des = "[{healthCheckComponent=BE4, healthCheckStatus=UP, version=0.0.1-SNAPSHOT, description=OK}, {healthCheckComponent=BE, healthCheckStatus=UP, version=1710.0.0-SNAPSHOT, description=OK}, {healthCheckComponent=BE5, healthCheckStatus=UP, version=2.1.9, description=OK}]"; + Type listType = new TypeToken>(){}.getType(); + List componentsInfo = new Gson().fromJson(des.toString(), listType); + System.out.println(componentsInfo.toString()); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckWrapper.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckWrapper.java index 184051600c..29c6350516 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckWrapper.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckWrapper.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,39 +24,39 @@ import java.util.List; public class HealthCheckWrapper { - private String sdcVersion; - private String siteMode; - private List componentsInfo; + String sdcVersion; + String siteMode; + List componentsInfo; - public HealthCheckWrapper(List componentsInfo, String sdcVersion, String siteMode) { - super(); - this.componentsInfo = componentsInfo; - this.sdcVersion = sdcVersion; - this.siteMode = siteMode; - } + public HealthCheckWrapper(List componentsInfo, String sdcVersion, String siteMode) { + super(); + this.componentsInfo = componentsInfo; + this.sdcVersion = sdcVersion; + this.siteMode = siteMode; + } - public List getComponentsInfo() { - return componentsInfo; - } + public List getComponentsInfo() { + return componentsInfo; + } - public void setComponentsInfo(List componentsInfo) { - this.componentsInfo = componentsInfo; - } + public void setComponentsInfo(List componentsInfo) { + this.componentsInfo = componentsInfo; + } - public String getSdcVersion() { - return sdcVersion; - } + public String getSdcVersion() { + return sdcVersion; + } - public void setSdcVersion(String sdcVersion) { - this.sdcVersion = sdcVersion; - } + public void setSdcVersion(String sdcVersion) { + this.sdcVersion = sdcVersion; + } - public String getSiteMode() { - return siteMode; - } + public String getSiteMode() { + return siteMode; + } - public void setSiteMode(String siteMode) { - this.siteMode = siteMode; - } + public void setSiteMode(String siteMode) { + this.siteMode = siteMode; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResourceType.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResourceType.java index f757f32a40..b93fed2e0c 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResourceType.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResourceType.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,5 +21,5 @@ package org.openecomp.sdc.common.api; public enum ResourceType { - RESOURCE, SERVICE + RESOURCE, SERVICE } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResponseInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResponseInfo.java index 290a71fb3b..3e8968a481 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResponseInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResponseInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,59 +25,59 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class ResponseInfo { - public enum ResponseStatusEnum { - SUCCESS("success"), LOGIN_FAILED("loginFailed"), INTERNAL_ERROR("internalError"), MISSING_HEADERS("required headers are missing"), TIMEOUT("timeout"), PARSING_ERROR("parsingFailed"); - - private String statusDescription; - - ResponseStatusEnum(String status) { - this.statusDescription = status; - } - - public String getStatusDescription() { - return statusDescription; - } - } - - private ResponseStatusEnum applicativeStatus; - private String description; - - public ResponseInfo(ResponseStatusEnum applicativeStatus, String description) { - super(); - this.applicativeStatus = applicativeStatus; - this.description = description; - } - - public ResponseInfo(ResponseStatusEnum applicativeStatus) { - super(); - this.applicativeStatus = applicativeStatus; - } - - public ResponseStatusEnum getApplicativeStatus() { - return applicativeStatus; - } - - public void setApplicativeStatus(ResponseStatusEnum applicativeStatus) { - this.applicativeStatus = applicativeStatus; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Override - public String toString() { - ObjectMapper mapper = new ObjectMapper(); - String tostring = super.toString(); - try { - tostring = mapper.writeValueAsString(this); - } catch (JsonProcessingException e) { - - } - return tostring; - } + public enum ResponseStatusEnum { + SUCCESS("success"), LOGIN_FAILED("loginFailed"), INTERNAL_ERROR("internalError"), MISSING_HEADERS("required headers are missing"), TIMEOUT("timeout"), PARSING_ERROR("parsingFailed"); + + private String statusDescription; + + ResponseStatusEnum(String status) { + this.statusDescription = status; + } + + public String getStatusDescription() { + return statusDescription; + } + } + + private ResponseStatusEnum applicativeStatus; + private String description; + + public ResponseInfo(ResponseStatusEnum applicativeStatus, String description) { + super(); + this.applicativeStatus = applicativeStatus; + this.description = description; + } + + public ResponseInfo(ResponseStatusEnum applicativeStatus) { + super(); + this.applicativeStatus = applicativeStatus; + } + + public ResponseStatusEnum getApplicativeStatus() { + return applicativeStatus; + } + + public void setApplicativeStatus(ResponseStatusEnum applicativeStatus) { + this.applicativeStatus = applicativeStatus; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + ObjectMapper mapper = new ObjectMapper(); + String tostring = super.toString(); + try { + tostring = mapper.writeValueAsString(this); + } catch (JsonProcessingException e) { + + } + return tostring; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ToscaNodeTypeInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ToscaNodeTypeInfo.java index 8246716566..f6608952d0 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ToscaNodeTypeInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ToscaNodeTypeInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,56 +24,56 @@ import java.util.List; public class ToscaNodeTypeInfo { - private String nodeName; - private String templateVersion; - private List interfaces; - private String iconPath; - private String templateName; - - public String getTemplateName() { - return templateName; - } - - public void setTemplateName(String templateName) { - this.templateName = templateName; - } - - public String getNodeName() { - return nodeName; - } - - public void setNodeName(String nodeName) { - this.nodeName = nodeName; - } - - public String getTemplateVersion() { - return templateVersion; - } - - public void setTemplateVersion(String templateVersion) { - this.templateVersion = templateVersion; - } - - public List getInterfaces() { - return interfaces; - } - - public void setInterfaces(List interfaces) { - this.interfaces = interfaces; - } - - public String getIconPath() { - return iconPath; - } - - public void setIconPath(String iconPath) { - this.iconPath = iconPath; - } - - @Override - public String toString() { - return "ToscaNodeTypeInfo [nodeName=" + nodeName + ", templateVersion=" + templateVersion + ", templateName=" - + templateName + ", interfaces=" + interfaces + ", iconPath=" + iconPath + "]"; - } + private String nodeName; + private String templateVersion; + private List interfaces; + private String iconPath; + private String templateName; + + public String getTemplateName() { + return templateName; + } + + public void setTemplateName(String templateName) { + this.templateName = templateName; + } + + public String getNodeName() { + return nodeName; + } + + public void setNodeName(String nodeName) { + this.nodeName = nodeName; + } + + public String getTemplateVersion() { + return templateVersion; + } + + public void setTemplateVersion(String templateVersion) { + this.templateVersion = templateVersion; + } + + public List getInterfaces() { + return interfaces; + } + + public void setInterfaces(List interfaces) { + this.interfaces = interfaces; + } + + public String getIconPath() { + return iconPath; + } + + public void setIconPath(String iconPath) { + this.iconPath = iconPath; + } + + @Override + public String toString() { + return "ToscaNodeTypeInfo [nodeName=" + nodeName + ", templateVersion=" + templateVersion + ", templateName=" + + templateName + ", interfaces=" + interfaces + ", iconPath=" + iconPath + "]"; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ToscaNodeTypeInterface.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ToscaNodeTypeInterface.java index 517ba8cc86..4095714f4b 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ToscaNodeTypeInterface.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ToscaNodeTypeInterface.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,14 +24,14 @@ import java.util.List; public class ToscaNodeTypeInterface { - private List scripts; + List scripts; - public List getScripts() { - return scripts; - } + public List getScripts() { + return scripts; + } - public void setScripts(List scripts) { - this.scripts = scripts; - } + public void setScripts(List scripts) { + this.scripts = scripts; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/UploadArtifactInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/UploadArtifactInfo.java index b168271257..110dbf34a2 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/UploadArtifactInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/UploadArtifactInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,134 +22,122 @@ package org.openecomp.sdc.common.api; public class UploadArtifactInfo { - public UploadArtifactInfo() { - - } - - public UploadArtifactInfo(String artifactName, String artifactPath, ArtifactTypeEnum artifactType, String artifactDescription) { - super(); - this.artifactName = artifactName; - this.artifactPath = artifactPath; - this.artifactType = artifactType; - this.artifactDescription = artifactDescription; - } - - public UploadArtifactInfo(String artifactName, String artifactPath, ArtifactTypeEnum artifactType, String artifactDescription, String artifactData) { - super(); - this.artifactName = artifactName; - this.artifactPath = artifactPath; - this.artifactType = artifactType; - this.artifactDescription = artifactDescription; - this.artifactData = artifactData; - } - - private String artifactName; - private String artifactPath; - private ArtifactTypeEnum artifactType; - private String artifactDescription; - private String artifactData; - - public String getArtifactName() { - return artifactName; - } - - public void setArtifactName(String artifactName) { - this.artifactName = artifactName; - } - - public String getArtifactPath() { - return artifactPath; - } - - public void setArtifactPath(String artifactPath) { - this.artifactPath = artifactPath; - } - - public ArtifactTypeEnum getArtifactType() { - return artifactType; - } - - public void setArtifactType(ArtifactTypeEnum artifactType) { - this.artifactType = artifactType; - } - - public String getArtifactDescription() { - return artifactDescription; - } - - public void setArtifactDescription(String artifactDescription) { - this.artifactDescription = artifactDescription; - } - - public String getArtifactData() { - return artifactData; - } - - public void setArtifactData(String artifactData) { - this.artifactData = artifactData; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((artifactData == null) ? 0 : artifactData.hashCode()); - result = prime * result + ((artifactDescription == null) ? 0 : artifactDescription.hashCode()); - result = prime * result + ((artifactName == null) ? 0 : artifactName.hashCode()); - result = prime * result + ((artifactPath == null) ? 0 : artifactPath.hashCode()); - result = prime * result + ((artifactType == null) ? 0 : artifactType.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - UploadArtifactInfo other = (UploadArtifactInfo) obj; - if (artifactData == null) { - if (other.artifactData != null) { - return false; - } - } else if (!artifactData.equals(other.artifactData)) { - return false; - } - if (artifactDescription == null) { - if (other.artifactDescription != null) { - return false; - } - } else if (!artifactDescription.equals(other.artifactDescription)) { - return false; - } - if (artifactName == null) { - if (other.artifactName != null) { - return false; - } - } else if (!artifactName.equals(other.artifactName)) { - return false; - } - if (artifactPath == null) { - if (other.artifactPath != null) { - return false; - } - } else if (!artifactPath.equals(other.artifactPath)) { - return false; - } - if (artifactType != other.artifactType) { - return false; - } - return true; - } - - @Override - public String toString() { - return "UploadArtifactInfo [artifactName=" + artifactName + ", artifactPath=" + artifactPath + ", artifactType=" + artifactType + ", artifactDescription=" + artifactDescription + ", artifactData=" + artifactData + "]"; - } + public UploadArtifactInfo() { + + } + + public UploadArtifactInfo(String artifactName, String artifactPath, ArtifactTypeEnum artifactType, String artifactDescription) { + super(); + this.artifactName = artifactName; + this.artifactPath = artifactPath; + this.artifactType = artifactType; + this.artifactDescription = artifactDescription; + } + + public UploadArtifactInfo(String artifactName, String artifactPath, ArtifactTypeEnum artifactType, String artifactDescription, String artifactData) { + super(); + this.artifactName = artifactName; + this.artifactPath = artifactPath; + this.artifactType = artifactType; + this.artifactDescription = artifactDescription; + this.artifactData = artifactData; + } + + private String artifactName; + private String artifactPath; + private ArtifactTypeEnum artifactType; + private String artifactDescription; + private String artifactData; + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public String getArtifactPath() { + return artifactPath; + } + + public void setArtifactPath(String artifactPath) { + this.artifactPath = artifactPath; + } + + public ArtifactTypeEnum getArtifactType() { + return artifactType; + } + + public void setArtifactType(ArtifactTypeEnum artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactDescription() { + return artifactDescription; + } + + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public String getArtifactData() { + return artifactData; + } + + public void setArtifactData(String artifactData) { + this.artifactData = artifactData; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((artifactData == null) ? 0 : artifactData.hashCode()); + result = prime * result + ((artifactDescription == null) ? 0 : artifactDescription.hashCode()); + result = prime * result + ((artifactName == null) ? 0 : artifactName.hashCode()); + result = prime * result + ((artifactPath == null) ? 0 : artifactPath.hashCode()); + result = prime * result + ((artifactType == null) ? 0 : artifactType.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + UploadArtifactInfo other = (UploadArtifactInfo) obj; + if (artifactData == null) { + if (other.artifactData != null) + return false; + } else if (!artifactData.equals(other.artifactData)) + return false; + if (artifactDescription == null) { + if (other.artifactDescription != null) + return false; + } else if (!artifactDescription.equals(other.artifactDescription)) + return false; + if (artifactName == null) { + if (other.artifactName != null) + return false; + } else if (!artifactName.equals(other.artifactName)) + return false; + if (artifactPath == null) { + if (other.artifactPath != null) + return false; + } else if (!artifactPath.equals(other.artifactPath)) + return false; + if (artifactType != other.artifactType) + return false; + return true; + } + + @Override + public String toString() { + return "UploadArtifactInfo [artifactName=" + artifactName + ", artifactPath=" + artifactPath + ", artifactType=" + artifactType + ", artifactDescription=" + artifactDescription + ", artifactData=" + artifactData + "]"; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/UserRoleEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/UserRoleEnum.java index 6e7b2403f3..a750fa454a 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/UserRoleEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/UserRoleEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,15 +21,15 @@ package org.openecomp.sdc.common.api; public enum UserRoleEnum { - ADMIN("ADMIN"), DESIGNER("DESIGNER"), TESTER("TESTER"), GOVERNOR("GOVERNOR"), OPS("OPS"), PRODUCT_MANAGER("PRODUCT_MANAGER"), PRODUCT_STRATEGIST("PRODUCT_STRATEGIST"); + ADMIN("ADMIN"), DESIGNER("DESIGNER"), TESTER("TESTER"), GOVERNOR("GOVERNOR"), OPS("OPS"), PRODUCT_MANAGER("PRODUCT_MANAGER"), PRODUCT_STRATEGIST("PRODUCT_STRATEGIST"); - private String name; + private String name; - UserRoleEnum(String name) { - this.name = name; - } + UserRoleEnum(String name) { + this.name = name; + } - public String getName() { - return name; - } + public String getName() { + return name; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/YamlConstants.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/YamlConstants.java index fe5e5288b0..0dadef9292 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/YamlConstants.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/YamlConstants.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,8 +22,8 @@ package org.openecomp.sdc.common.api; public interface YamlConstants { - String NODE_TYPES = "node_types"; - String INTERFACES = "interfaces"; - String TEMPLATE_VERSION = "template_version"; - String TEMPLATE_NAME = "template_name"; + public static final String NODE_TYPES = "node_types"; + public static final String INTERFACES = "interfaces"; + public static final String TEMPLATE_VERSION = "template_version"; + public static final String TEMPLATE_NAME = "template_name"; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/YamlSuffixEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/YamlSuffixEnum.java index 8daf335c25..1310ab170f 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/YamlSuffixEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/YamlSuffixEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,36 +25,36 @@ import java.util.List; public enum YamlSuffixEnum { - YAML("YAML"), + YAML("YAML"), - yaml("yaml"), + yaml("yaml"), - YML("YML"), + YML("YML"), - yml("yml"); + yml("yml"); - YamlSuffixEnum(String suffix) { - this.suffix = suffix; - } + YamlSuffixEnum(String suffix) { + this.suffix = suffix; + } - private String suffix; + private String suffix; - public String getSuffix() { - return suffix; - } + public String getSuffix() { + return suffix; + } - public void setSuufix(String suffix) { - this.suffix = suffix; - } + public void setSuufix(String suffix) { + this.suffix = suffix; + } - public static List getSuffixes() { + public static List getSuffixes() { - List arrayList = new ArrayList<>(); + List arrayList = new ArrayList<>(); - for (YamlSuffixEnum yamlSuffixEnum : YamlSuffixEnum.values()) { - arrayList.add(yamlSuffixEnum.getSuffix()); - } + for (YamlSuffixEnum yamlSuffixEnum : YamlSuffixEnum.values()) { + arrayList.add(yamlSuffixEnum.getSuffix()); + } - return arrayList; - } + return arrayList; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/AbsEcompErrorManager.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/AbsEcompErrorManager.java index 22df432afe..49f04d2ee1 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/AbsEcompErrorManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/AbsEcompErrorManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,14 +25,14 @@ import com.jcabi.aspects.Loggable; @Loggable(prepend = true, value = Loggable.TRACE, trim = false) public abstract class AbsEcompErrorManager { - public static final String PARAM_STR = "%s"; + public static final String PARAM_STR = "%s"; - public abstract IEcompConfigurationManager getConfigurationManager(); + public abstract IEcompConfigurationManager getConfigurationManager(); - public void processEcompError(String context, EcompErrorEnum ecompErrorEnum, String... descriptionParams) { + public void processEcompError(String context, EcompErrorEnum ecompErrorEnum, String... descriptionParams) { - EcompErrorLogUtil.logEcompError(context, ecompErrorEnum, descriptionParams); + EcompErrorLogUtil.logEcompError(context, ecompErrorEnum, descriptionParams); - } + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompClassification.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompClassification.java index fc5a2f0512..31499486de 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompClassification.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompClassification.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,20 +22,20 @@ package org.openecomp.sdc.common.config; public enum EcompClassification { - INFORMATION("I"), WARNING("W"), ERROR("E"), FATAL("F"); + INFORMATION("I"), WARNING("W"), ERROR("E"), FATAL("F"); - private String classification; + String classification; - EcompClassification(String classification) { - this.classification = classification; - } + EcompClassification(String classification) { + this.classification = classification; + } - public String getClassification() { - return classification; - } + public String getClassification() { + return classification; + } - public void setClassification(String classification) { - this.classification = classification; - } + public void setClassification(String classification) { + this.classification = classification; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java index 0763f9052e..e605366fcb 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java @@ -34,19 +34,19 @@ public enum EcompErrorCode { "Unable to connect to a valid ASDC Backend Server", "Please check connectivity from this FE instance towards BE or BE Load Balancer. Please check that parameters in FE configuration.yaml: beHost, beHttpPort and beSslPort point to a valid host and port values."), - E_205("ASDC Backend Recovery to either one of the following components: JanusGraph DB, Cassandra, Onboarding, UEB Cluster."), E_206( - "ASDC Backend connection recovery to JanusGraph DB."), E_207( - "ASDC Backend connection recovery to ElasticSearch."), E_208( - "ASDC Backend connection recovery to UEB Cluster."), E_209( - "Connectivity to ASDC BE Server is recovered."), E_210( - "Connection problem towards U-EB server. Reason: %s", - "Please check that that parameter uebServers in distribution-configuration.yaml points to a valid UEB Cluster."), E_211( - "Connection problem towards U-EB server. Cannot reach host %s", - "Please check that that parameter uebServers in distribution-configuration.yaml points to a valid UEB Cluster."), E_212( - "Couldn't resolve hostIP. Desciption: %s"), E_213( - "Site switch over was done. Site is now in %s mode"), E_214( - "Dmaap Connection problem."), E_299( - "Internal Connection problem. Description: %s"), + E_205("ASDC Backend Recovery to either one of the following components: JanusGraph DB, Cassandra, Onboarding, UEB Cluster."), E_206( + "ASDC Backend connection recovery to JanusGraph DB."), E_208( + "ASDC Backend connection recovery to UEB Cluster."), E_209( + "Connectivity to ASDC BE Server is recovered."), E_210( + "Connection problem towards U-EB server. Reason: %s", + "Please check that that parameter uebServers in distribution-configuration.yaml points to a valid UEB Cluster."), E_211( + "Connection problem towards U-EB server. Cannot reach host %s", + "Please check that that parameter uebServers in distribution-configuration.yaml points to a valid UEB Cluster."), E_212( + "Couldn't resolve hostIP. Desciption: %s"), E_213( + "Site switch over was done. Site is now in %s mode"), E_214( + "Dmaap Connection problem."), E_220( + "User HTTP session is expired"), E_299( + "Internal Connection problem. Description: %s"), // [resource/service/product] E_300("Mandatory %s Component %s cannot be found in repository"), diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorConfiguration.java index 89f4d17977..b44ceea678 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,6 +21,7 @@ package org.openecomp.sdc.common.config; import org.openecomp.sdc.common.api.BasicConfiguration; +import org.openecomp.sdc.common.log.enums.EcompErrorSeverity; import java.util.Arrays; import java.util.HashMap; @@ -29,135 +30,133 @@ import java.util.regex.Pattern; public class EcompErrorConfiguration extends BasicConfiguration { - private static final int LOWEST_ERROR_VALID_CODE = 3010; - private static final int HIGHEST_ERROR_VALID_CODE = 9999; - private Map errors = new HashMap<>(); - static final String ECODE_PREFIX = "ASDC_"; - private static final Pattern ECODE_PATTERN = Pattern.compile("^" + ECODE_PREFIX + "\\d{4}$"); - - public Map getErrors() { - return errors; - } - - public void setErrors(Map errors) { - // Validating ecomp-error-configuration.yaml - for (Map.Entry ecompErrorInfo : errors.entrySet()) { - String ecompErrorName = ecompErrorInfo.getKey(); - EcompErrorInfo res = validateEcompErrorInfo(ecompErrorName, ecompErrorInfo.getValue()); - if (res != null) { - // Validation failed! - EcompErrorLogUtil.logEcompError(EcompErrorName.EcompConfigFileFormat, res, this.getClass().getName()); - return; - } - } - // Validation passed - this.errors = errors; - } - - public EcompErrorInfo getEcompErrorInfo(String key) { - EcompErrorInfo clone = null; - EcompErrorInfo other = errors.get(key); - if (other != null) { - clone = new EcompErrorInfo(); - clone.cloneData(other); - } - return clone; - } - - protected EcompErrorInfo validateEcompErrorInfo(String ecompErrorName, EcompErrorInfo ecompErrorInfoToValidate) { - if (ecompErrorInfoToValidate == null) { - return getErrorInfoForConfigFile("error " + ecompErrorName + " not found "); - } - String type = ecompErrorInfoToValidate.getType(); - if (type == null) { - return getErrorInfoForConfigFile("empty error type for error " + ecompErrorName - + ", value should be one of the following: " + Arrays.asList(EcompErrorType.values())); - } - try { - EcompErrorType.valueOf(type); - } catch (IllegalArgumentException e) { - return getErrorInfoForConfigFile("error type " + type + " is invalid for error " + ecompErrorName - + ", value should be one of the following: " + Arrays.asList(EcompErrorType.values())); - } - - String severity = ecompErrorInfoToValidate.getSeverity(); - if (severity == null) { - return getErrorInfoForConfigFile("empty error severity for error " + ecompErrorName - + ", value should be one of the following: " + Arrays.asList(EcompErrorSeverity.values())); - } - try { - EcompErrorSeverity.valueOf(severity); - } catch (IllegalArgumentException e) { - return getErrorInfoForConfigFile("error severity " + severity + " is invalid for error " + ecompErrorName - + ", value should be one of the following: " + Arrays.asList(EcompErrorSeverity.values())); - } - String alarmSeverity = ecompErrorInfoToValidate.getAlarmSeverity(); - if (alarmSeverity == null) { - return getErrorInfoForConfigFile("empty error alarm for error " + ecompErrorName - + ", , value should be one of the following: " + Arrays.asList(EcompAlarmSeverity.values())); - } - try { - EcompAlarmSeverity.valueOf(alarmSeverity); - } catch (IllegalArgumentException e) { - return getErrorInfoForConfigFile("error alarm severity " + alarmSeverity + " is invalid for error " - + ecompErrorName + ", , value should be one of the following: " - + Arrays.asList(EcompAlarmSeverity.values())); - } - - String code = ecompErrorInfoToValidate.getCode(); - if (code != null && ECODE_PATTERN.matcher(code).matches()) { - String[] split = code.split("_"); - int parseInt = Integer.parseInt(split[1]); - if (parseInt < LOWEST_ERROR_VALID_CODE || parseInt > HIGHEST_ERROR_VALID_CODE) { - return getErrorInfoForInvalidCode(code, ecompErrorName); - } - } else { - return getErrorInfoForInvalidCode(code, ecompErrorName); - } - return null; - } - - private EcompErrorInfo getErrorInfoForInvalidCode(String code, String ecompErrorName) { - return getErrorInfoForConfigFile("error code " + code + " is invalid for error " + ecompErrorName - + ", should be in format ASDC_[3010-9999]"); - } - - private EcompErrorInfo getErrorInfoForConfigFile(String errorMessage) { - EcompErrorInfo ecompErrorInfo = new EcompErrorInfo(); - ecompErrorInfo.setCode(ECODE_PREFIX + "3000"); - ecompErrorInfo.setType(EcompErrorType.CONFIG_ERROR.name()); - ecompErrorInfo.setSeverity(EcompErrorSeverity.FATAL.name()); - ecompErrorInfo.setAlarmSeverity(EcompAlarmSeverity.CRITICAL.name()); - ecompErrorInfo.setDescription(errorMessage); - return ecompErrorInfo; - } - - @Override - public String toString() { - return "EcompErrorConfiguration [errors=" + errors + "]"; - } - - /******************************* - * enums - */ - - public enum EcompErrorType { - RECOVERY, CONFIG_ERROR, SYSTEM_ERROR, DATA_ERROR, CONNECTION_PROBLEM, AUTHENTICATION_PROBLEM; - } - - public enum EcompAlarmSeverity { - CRITICAL, MAJOR, MINOR, INFORMATIONAL, NONE; - } - - public enum EcompErrorSeverity { - INFO, WARN, ERROR, FATAL; - } - - public enum EcompErrorSeverityPrefix { - I, W, E, F; - } - - public static void main(String[] args) { - System.out.println(Arrays.asList(EcompErrorType.values())); - } + private Map errors = new HashMap<>(); + static final String ECODE_PREFIX = "ASDC_"; + private static final Pattern ECODE_PATTERN = Pattern.compile("^" + ECODE_PREFIX + "\\d{4}$"); + + public Map getErrors() { + return errors; + } + + public void setErrors(Map errors) { + // Validating ecomp-error-configuration.yaml + for (Map.Entry ecompErrorInfo : errors.entrySet()) { + String ecompErrorName = ecompErrorInfo.getKey(); + EcompErrorInfo res = validateEcompErrorInfo(ecompErrorName, ecompErrorInfo.getValue()); + if (res != null) { + // Validation failed! + EcompErrorLogUtil.logEcompError(EcompErrorName.EcompConfigFileFormat, res, this.getClass().getName()); + return; + } + } + // Validation passed + this.errors = errors; + } + + public EcompErrorInfo getEcompErrorInfo(String key) { + EcompErrorInfo clone = null; + EcompErrorInfo other = errors.get(key); + if (other != null) { + clone = new EcompErrorInfo(); + clone.cloneData(other); + } + return clone; + } + + protected EcompErrorInfo validateEcompErrorInfo(String ecompErrorName, EcompErrorInfo ecompErrorInfoToValidate) { + if (ecompErrorInfoToValidate == null) { + return getErrorInfoForConfigFile("error " + ecompErrorName + " not found "); + } + String type = ecompErrorInfoToValidate.getType(); + if (type == null) { + return getErrorInfoForConfigFile("empty error type for error " + ecompErrorName + + ", value should be one of the following: " + Arrays.asList(EcompErrorType.values())); + } + try { + EcompErrorType.valueOf(type); + } catch (IllegalArgumentException e) { + return getErrorInfoForConfigFile("error type " + type + " is invalid for error " + ecompErrorName + + ", value should be one of the following: " + Arrays.asList(EcompErrorType.values())); + } + + String severity = ecompErrorInfoToValidate.getSeverity(); + if (severity == null) { + return getErrorInfoForConfigFile("empty error severity for error " + ecompErrorName + + ", value should be one of the following: " + Arrays.asList(EcompErrorSeverity.values())); + } + try { + EcompErrorSeverity.valueOf(severity); + } catch (IllegalArgumentException e) { + return getErrorInfoForConfigFile("error severity " + severity + " is invalid for error " + ecompErrorName + + ", value should be one of the following: " + Arrays.asList(EcompErrorSeverity.values())); + } + String alarmSeverity = ecompErrorInfoToValidate.getAlarmSeverity(); + if (alarmSeverity == null) { + return getErrorInfoForConfigFile("empty error alarm for error " + ecompErrorName + + ", , value should be one of the following: " + Arrays.asList(EcompAlarmSeverity.values())); + } + try { + EcompAlarmSeverity.valueOf(alarmSeverity); + } catch (IllegalArgumentException e) { + return getErrorInfoForConfigFile("error alarm severity " + alarmSeverity + " is invalid for error " + + ecompErrorName + ", , value should be one of the following: " + + Arrays.asList(EcompAlarmSeverity.values())); + } + + String code = ecompErrorInfoToValidate.getCode(); + if (code != null && ECODE_PATTERN.matcher(code).matches()) { + String[] split = code.split("_"); + int parseInt = Integer.parseInt(split[1]); + if (parseInt < 3010 || parseInt > 9999) { + return getErrorInfoForInvalidCode(code, ecompErrorName); + } + } else { + return getErrorInfoForInvalidCode(code, ecompErrorName); + } + return null; + } + + private EcompErrorInfo getErrorInfoForInvalidCode(String code, String ecompErrorName) { + return getErrorInfoForConfigFile("error code " + code + " is invalid for error " + ecompErrorName + + ", should be in format ASDC_[3010-9999]"); + } + + private EcompErrorInfo getErrorInfoForConfigFile(String errorMessage) { + EcompErrorInfo ecompErrorInfo = new EcompErrorInfo(); + ecompErrorInfo.setCode(ECODE_PREFIX + "3000"); + ecompErrorInfo.setType(EcompErrorType.CONFIG_ERROR.name()); + ecompErrorInfo.setSeverity(EcompErrorSeverity.FATAL.name()); + ecompErrorInfo.setAlarmSeverity(EcompAlarmSeverity.CRITICAL.name()); + ecompErrorInfo.setDescription(errorMessage); + return ecompErrorInfo; + } + + @Override + public String toString() { + return "EcompErrorConfiguration [errors=" + errors + "]"; + } + + /******************************* + * enums + */ + + public enum EcompErrorType { + RECOVERY, CONFIG_ERROR, SYSTEM_ERROR, DATA_ERROR, CONNECTION_PROBLEM, AUTHENTICATION_PROBLEM; + } + + public enum EcompAlarmSeverity { + CRITICAL, MAJOR, MINOR, INFORMATIONAL, NONE; + } + + public enum EcompErrorSeverity { + INFO, WARN, ERROR, FATAL; + } + + public enum EcompErrorSeverityPrefix { + I, W, E, F; + } + + public static void main(String[] args) { + System.out.println(Arrays.asList(EcompErrorType.values())); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java index 58e19a7347..bed7255057 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java @@ -30,6 +30,9 @@ public enum EcompErrorEnum { DmaapHealthCheckError(EcompErrorCode.E_214, ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MAJOR, EcompClassification.ERROR), + SessionExpiredAuthenticationError(EcompErrorCode.E_220, ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.MAJOR, + EcompClassification.ERROR), + InternalAuthenticationInfo(EcompErrorCode.E_199, ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION), InternalAuthenticationWarning(EcompErrorCode.E_199, ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.MINOR, @@ -42,8 +45,6 @@ public enum EcompErrorEnum { BeHealthCheckRecovery(EcompErrorCode.E_205, ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, null), BeHealthCheckJanusGraphRecovery(EcompErrorCode.E_206, ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, - null), BeHealthCheckElasticSearchRecovery(EcompErrorCode.E_207, ErrorType.RECOVERY, - AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, null), BeHealthCheckUebClusterRecovery(EcompErrorCode.E_208, ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, null), FeHealthCheckRecovery(EcompErrorCode.E_209, ErrorType.RECOVERY, @@ -55,9 +56,8 @@ public enum EcompErrorEnum { BeHealthCheckRecovery), BeHealthCheckJanusGraphError(EcompErrorCode.E_201, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, - EcompClassification.ERROR, BeHealthCheckJanusGraphRecovery), BeHealthCheckElasticSearchError( - EcompErrorCode.E_202, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.ERROR, - BeHealthCheckElasticSearchRecovery), BeHealthCheckUebClusterError(EcompErrorCode.E_203, + EcompClassification.ERROR, BeHealthCheckJanusGraphRecovery), + BeHealthCheckUebClusterError(EcompErrorCode.E_203, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.ERROR, BeHealthCheckUebClusterRecovery), FeHealthCheckError(EcompErrorCode.E_204, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.ERROR, @@ -410,11 +410,13 @@ public enum EcompErrorEnum { * AlarmSeverity.CRITICAL, EcompClassification.FATAL), */; - private EcompErrorCode ecompErrorCode; - private ErrorType eType; - private AlarmSeverity alarmSeverity; - private EcompClassification classification; - private EcompErrorEnum clearCode; + ; + + EcompErrorCode ecompErrorCode; + ErrorType eType; + AlarmSeverity alarmSeverity; + EcompClassification classification; + EcompErrorEnum clearCode; EcompErrorEnum(EcompErrorCode ecompErrorCode, ErrorType eType, AlarmSeverity alarmSeverity, EcompClassification classification, EcompErrorEnum clearCode) { diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorInfo.java index 75ad74c56b..e1fd34b26d 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,57 +22,57 @@ package org.openecomp.sdc.common.config; public class EcompErrorInfo { - private String type; - private String code; - private String severity; - private String description; - private String alarmSeverity; + private String type; + private String code; + private String severity; + private String description; + private String alarmSeverity; - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getCode() { - return code; - } + public String getCode() { + return code; + } - public void setCode(String code) { - this.code = code; - } + public void setCode(String code) { + this.code = code; + } - public String getSeverity() { - return severity; - } + public String getSeverity() { + return severity; + } - public void setSeverity(String severity) { - this.severity = severity; - } + public void setSeverity(String severity) { + this.severity = severity; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public String getAlarmSeverity() { - return alarmSeverity; - } + public String getAlarmSeverity() { + return alarmSeverity; + } - public void setAlarmSeverity(String alarmSeverity) { - this.alarmSeverity = alarmSeverity; - } + public void setAlarmSeverity(String alarmSeverity) { + this.alarmSeverity = alarmSeverity; + } - public void cloneData(EcompErrorInfo other) { - this.type = other.getType(); - this.severity = other.getSeverity(); - this.description = other.getDescription(); - this.code = other.getCode(); - this.alarmSeverity = other.getAlarmSeverity(); - } + public void cloneData(EcompErrorInfo other) { + this.type = other.getType(); + this.severity = other.getSeverity(); + this.description = other.getDescription(); + this.code = other.getCode(); + this.alarmSeverity = other.getAlarmSeverity(); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorLogUtil.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorLogUtil.java index 933b510e91..feb3ea6e68 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorLogUtil.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorLogUtil.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,7 +22,7 @@ package org.openecomp.sdc.common.config; import fj.data.Either; import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.common.config.EcompErrorConfiguration.EcompErrorSeverity; +import org.openecomp.sdc.common.log.enums.EcompErrorSeverity; import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; import org.openecomp.sdc.common.log.wrappers.Logger; import org.slf4j.MDC; @@ -33,133 +33,133 @@ import java.util.Locale; public class EcompErrorLogUtil { - private static final String ECOMP_ERROR_TMPL = "ETYPE = \"%s\" ENAME = \"%s\" ECODE = \"%s\" ECONTEXT = \"%s\" EDESC = \"%s\""; - private static Logger log = Logger.getLogger(EcompErrorLogUtil.class.getName()); - private static final String FATAL_ERROR_PREFIX = "FATAL ERROR!! "; - - public static void logEcompError(EcompErrorName ecompErrorName, EcompErrorInfo ecompErrorInfo, - String ecompErrorContext, String... ecompDescriptionParams) { - if (ecompErrorInfo != null) { - StringBuilder sb = new StringBuilder(); - Formatter formatter = new Formatter(sb, Locale.US); - try { - String description = ecompErrorInfo.getDescription(); - String severityStr = ecompErrorInfo.getSeverity(); - EcompErrorConfiguration.EcompErrorSeverity severity = EcompErrorSeverity.ERROR; - // Since there is no FATAL log level, this is how we distinguish - // the FATAL errors - if (severityStr.equals(EcompErrorConfiguration.EcompErrorSeverity.FATAL.name())) { - description = FATAL_ERROR_PREFIX + description; - severity = EcompErrorSeverity.FATAL; - } else if (severityStr.equals(EcompErrorConfiguration.EcompErrorSeverity.WARN.name())) { - severity = EcompErrorSeverity.WARN; - } else if (severityStr.equals(EcompErrorConfiguration.EcompErrorSeverity.INFO.name())) { - severity = EcompErrorSeverity.INFO; - } - - MDC.put("alarmSeverity", ecompErrorInfo.getAlarmSeverity()); - // else it stays ERROR - formatter.format(ECOMP_ERROR_TMPL, ecompErrorInfo.getType(), ecompErrorName.name(), - ecompErrorInfo.getCode(), ecompErrorContext, description); + private static String ECOMP_ERROR_TMPL = "ETYPE = \"%s\" ENAME = \"%s\" ECODE = \"%s\" ECONTEXT = \"%s\" EDESC = \"%s\""; + private static Logger log = Logger.getLogger(EcompErrorLogUtil.class.getName()); + private static final String FATAL_ERROR_PREFIX = "FATAL ERROR!! "; + + public static void logEcompError(EcompErrorName ecompErrorName, EcompErrorInfo ecompErrorInfo, + String ecompErrorContext, String... ecompDescriptionParams) { + if (ecompErrorInfo != null) { + StringBuilder sb = new StringBuilder(); + Formatter formatter = new Formatter(sb, Locale.US); + try { + String description = ecompErrorInfo.getDescription(); + String severityStr = ecompErrorInfo.getSeverity(); + EcompErrorSeverity severity = EcompErrorSeverity.ERROR; + // Since there is no FATAL log level, this is how we distinguish + // the FATAL errors + if (severityStr.equals(EcompErrorSeverity.FATAL.name())) { + description = FATAL_ERROR_PREFIX + description; + severity = EcompErrorSeverity.FATAL; + } else if (severityStr.equals(EcompErrorSeverity.WARN.name())) { + severity = EcompErrorSeverity.WARN; + } else if (severityStr.equals(EcompErrorSeverity.INFO.name())) { + severity = EcompErrorSeverity.INFO; + } + + MDC.put("alarmSeverity", ecompErrorInfo.getAlarmSeverity()); + // else it stays ERROR + formatter.format(ECOMP_ERROR_TMPL, ecompErrorInfo.getType(), ecompErrorName.name(), + ecompErrorInfo.getCode(), ecompErrorContext, description); log.error(severity, EcompLoggerErrorCode.getByValue(ecompErrorInfo.getCode()), ecompErrorContext, ecompErrorContext, description); } finally { - formatter.close(); - MDC.remove("alarmSeverity"); - } - } - } - - public static void logEcompError(String ecompErrorContext, EcompErrorEnum ecompErrorEnum, - String... ecompDescriptionParams) { - logEcompError(ecompErrorContext, ecompErrorEnum, true, ecompDescriptionParams); - } - - public static void logEcompError(String ecompErrorContext, EcompErrorEnum ecompErrorEnum, boolean logMissingParams, - String... ecompDescriptionParams) { - StringBuilder sb = new StringBuilder(); - Formatter formatter = new Formatter(sb, Locale.US); - try { - String description; - - Either setDescriptionParamsResult = setDescriptionParams(ecompErrorEnum, - ecompDescriptionParams); - if (setDescriptionParamsResult.isLeft()) { - description = setDescriptionParamsResult.left().value(); - } else { - EcompErrorEnum mismatchErrorEnum = EcompErrorEnum.EcompMismatchParam; - if (logMissingParams) { - logEcompError("logEcompError", mismatchErrorEnum, false, ecompErrorEnum.name()); - } else { - log.info("Failed to log the error code {}", mismatchErrorEnum); - } - return; - } - EcompClassification classification = ecompErrorEnum.getClassification(); - - EcompErrorConfiguration.EcompErrorSeverity severity = EcompErrorSeverity.ERROR; - // Since there is no FATAL log level, this is how we distinguish the - // FATAL errors - if (classification == EcompClassification.FATAL) { - description = FATAL_ERROR_PREFIX + description; - severity = EcompErrorSeverity.FATAL; - } else if (classification == EcompClassification.WARNING) { - severity = EcompErrorSeverity.WARN; - } else if (classification == EcompClassification.INFORMATION) { - severity = EcompErrorSeverity.INFO; - } - - String eCode = createEcode(ecompErrorEnum); - - MDC.put("alarmSeverity", ecompErrorEnum.getAlarmSeverity().name()); - // else it stays ERROR - formatter.format(ECOMP_ERROR_TMPL, ecompErrorEnum.geteType(), ecompErrorEnum.name(), eCode, - ecompErrorContext, description); + formatter.close(); + MDC.remove("alarmSeverity"); + } + } + } + + public static void logEcompError(String ecompErrorContext, EcompErrorEnum ecompErrorEnum, + String... ecompDescriptionParams) { + logEcompError(ecompErrorContext, ecompErrorEnum, true, ecompDescriptionParams); + } + + public static void logEcompError(String ecompErrorContext, EcompErrorEnum ecompErrorEnum, boolean logMissingParams, + String... ecompDescriptionParams) { + StringBuilder sb = new StringBuilder(); + Formatter formatter = new Formatter(sb, Locale.US); + try { + String description; + + Either setDescriptionParamsResult = setDescriptionParams(ecompErrorEnum, + ecompDescriptionParams); + if (setDescriptionParamsResult.isLeft()) { + description = setDescriptionParamsResult.left().value(); + } else { + EcompErrorEnum mismatchErrorEnum = EcompErrorEnum.EcompMismatchParam; + if (logMissingParams) { + logEcompError("logEcompError", mismatchErrorEnum, false, ecompErrorEnum.name()); + } else { + log.info("Failed to log the error code {}", mismatchErrorEnum); + } + return; + } + EcompClassification classification = ecompErrorEnum.getClassification(); + + EcompErrorSeverity severity = EcompErrorSeverity.ERROR; + // Since there is no FATAL log level, this is how we distinguish the + // FATAL errors + if (classification == EcompClassification.FATAL) { + description = FATAL_ERROR_PREFIX + description; + severity = EcompErrorSeverity.FATAL; + } else if (classification == EcompClassification.WARNING) { + severity = EcompErrorSeverity.WARN; + } else if (classification == EcompClassification.INFORMATION) { + severity = EcompErrorSeverity.INFO; + } + + String eCode = createEcode(ecompErrorEnum); + + MDC.put("alarmSeverity", ecompErrorEnum.alarmSeverity.name()); + // else it stays ERROR + formatter.format(ECOMP_ERROR_TMPL, ecompErrorEnum.geteType(), ecompErrorEnum.name(), eCode, + ecompErrorContext, description); log.error(severity, EcompLoggerErrorCode.getByValue(ecompErrorEnum.getEcompErrorCode().name()), ecompErrorContext, ecompErrorContext, description); - } finally { - formatter.close(); - MDC.remove("alarmSeverity"); - } - } + } finally { + formatter.close(); + MDC.remove("alarmSeverity"); + } + } - public static String createEcode(EcompErrorEnum ecompErrorEnum) { + public static String createEcode(EcompErrorEnum ecompErrorEnum) { - EcompClassification classification = ecompErrorEnum.getClassification(); - String ecompErrorCode = ecompErrorEnum.getEcompErrorCode().name(); + EcompClassification classification = ecompErrorEnum.getClassification(); + String ecompErrorCode = ecompErrorEnum.getEcompErrorCode().name(); - String ecodeNumber = ecompErrorCode.substring(ecompErrorCode.indexOf("_") + 1); + String ecodeNumber = ecompErrorCode.substring(ecompErrorCode.indexOf("_") + 1); return "ASDC" + ecodeNumber + classification.getClassification(); - } - - private static Either setDescriptionParams(EcompErrorEnum ecompErrorEnum, - String... descriptionParams) { - String description = ecompErrorEnum.getEcompErrorCode().getDescription(); - - // Counting number of params in description - int countMatches = StringUtils.countMatches(description, AbsEcompErrorManager.PARAM_STR); - // Catching cases when there are more params passed than there are in - // the description (formatter will ignore extra params and won't throw - // exception) - if (countMatches != descriptionParams.length) { - return Either.right(false); - } - // Setting params of the description if any - StringBuilder sb = new StringBuilder(); - Formatter formatter = new Formatter(sb, Locale.US); - try { - formatter.format(description, (Object[]) descriptionParams).toString(); - return Either.left(formatter.toString()); - } catch (IllegalFormatException e) { - // Number of passed params doesn't match number of params in config - // file - return Either.right(false); - } finally { - formatter.close(); - } - - } + } + + private static Either setDescriptionParams(EcompErrorEnum ecompErrorEnum, + String... descriptionParams) { + String description = ecompErrorEnum.getEcompErrorCode().getDescription(); + + // Counting number of params in description + int countMatches = StringUtils.countMatches(description, AbsEcompErrorManager.PARAM_STR); + // Catching cases when there are more params passed than there are in + // the description (formatter will ignore extra params and won't throw + // exception) + if (countMatches != descriptionParams.length) { + return Either.right(false); + } + // Setting params of the description if any + StringBuilder sb = new StringBuilder(); + Formatter formatter = new Formatter(sb, Locale.US); + try { + formatter.format(description, (Object[]) descriptionParams).toString(); + return Either.left(formatter.toString()); + } catch (IllegalFormatException e) { + // Number of passed params doesn't match number of params in config + // file + return Either.right(false); + } finally { + formatter.close(); + } + + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorName.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorName.java index b33bc45520..5da7808376 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorName.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorName.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,23 +21,23 @@ package org.openecomp.sdc.common.config; public enum EcompErrorName { - // general - EcompConfigFileFormat, EcompErrorNotFound, EcompErrorDescParamsMismatch, + // general + EcompConfigFileFormat, EcompErrorNotFound, EcompErrorDescParamsMismatch, - // FE - FeHealthCheckConnectionError, FeHealthCheckRecovery /* Recovery */, FeHttpLoggingError, FePortalServletError, FeHealthCheckGeneralError, + // FE + FeHealthCheckConnectionError, FeHealthCheckRecovery /* Recovery */, FeHttpLoggingError, FePortalServletError, FeHealthCheckGeneralError, - // BE section here... - BeHealthCheckError, BeHealthCheckRecovery, /* Recovery */ - BeRestApiGeneralError, BeInitializationError, BeResourceMissingError, BeServiceMissingError, BeMissingArtifactInformationError, BeArtifactMissingError, BeArtifactPayloadInvalid, BeUserMissingError, BeArtifactInformationInvalidError, BeIncorrectServiceError, BeFailedAddingResourceInstanceError, - // BeFailedDeletingResourceInstanceError, - BeFailedAddingCapabilityTypeError, BeCapabilityTypeMissingError, BeInterfaceMissingError, - // BeRepositoryObjectNotFoundError, - // BeRepositoryDeleteError, - // BeRepositoryQueryError, - BeDaoSystemError, BeSystemError, BeInvalidConfigurationError, BeMissingConfigurationError, BeUebConnectionError, BeUebObjectNotFoundError, BeUebSystemError, BeDistributionEngineSystemError, BeDistributionEngineInvalidArtifactType, BeConfigurationInvalidListSizeError, BeUebAuthenticationError, BeUebUnkownHostError, BeInvalidTypeError, BeInvalidValueError, BeFailedLockObjectError, BeInvalidJsonInput, BeDistributionMissingError, ErrorConfigFileFormat, - // model - BeFailedCreateNodeError, BeFailedUpdateNodeError, BeFailedDeleteNodeError, BeFailedRetrieveNodeError, BeExecuteRollbackError, BeFailedFindParentError, BeFailedFindAllNodesError, BeFailedFindAssociationError, BeFailedToAssociateError, BeComponentCleanerSystemError, - //dmaap - DmaapHealthCheckRecovery, DmaapHealthCheckError; + // BE section here... + BeHealthCheckError, BeHealthCheckRecovery, /* Recovery */ + BeRestApiGeneralError, BeInitializationError, BeResourceMissingError, BeServiceMissingError, BeMissingArtifactInformationError, BeArtifactMissingError, BeArtifactPayloadInvalid, BeUserMissingError, BeArtifactInformationInvalidError, BeIncorrectServiceError, BeFailedAddingResourceInstanceError, + // BeFailedDeletingResourceInstanceError, + BeFailedAddingCapabilityTypeError, BeCapabilityTypeMissingError, BeInterfaceMissingError, + // BeRepositoryObjectNotFoundError, + // BeRepositoryDeleteError, + // BeRepositoryQueryError, + BeDaoSystemError, BeSystemError, BeInvalidConfigurationError, BeMissingConfigurationError, BeUebConnectionError, BeUebObjectNotFoundError, BeUebSystemError, BeDistributionEngineSystemError, BeDistributionEngineInvalidArtifactType, BeConfigurationInvalidListSizeError, BeUebAuthenticationError, BeUebUnkownHostError, BeInvalidTypeError, BeInvalidValueError, BeFailedLockObjectError, BeInvalidJsonInput, BeDistributionMissingError, ErrorConfigFileFormat, + // model + BeFailedCreateNodeError, BeFailedUpdateNodeError, BeFailedDeleteNodeError, BeFailedRetrieveNodeError, BeExecuteRollbackError, BeFailedFindParentError, BeFailedFindAllNodesError, BeFailedFindAssociationError, BeFailedToAssociateError, BeComponentCleanerSystemError, + //dmaap + DmaapHealthCheckRecovery , DmaapHealthCheckError; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/IEcompConfigurationManager.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/IEcompConfigurationManager.java index 3ecfa7914a..c16d8d329b 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/IEcompConfigurationManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/IEcompConfigurationManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,5 +21,5 @@ package org.openecomp.sdc.common.config; public interface IEcompConfigurationManager { - EcompErrorConfiguration getEcompErrorConfiguration(); + public EcompErrorConfiguration getEcompErrorConfiguration(); } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/generation/GenerateEcompErrorsCsv.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/generation/GenerateEcompErrorsCsv.java index d46ead42a9..f59385e2f5 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/generation/GenerateEcompErrorsCsv.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/generation/GenerateEcompErrorsCsv.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,8 +24,6 @@ import org.openecomp.sdc.common.config.EcompErrorEnum; import org.openecomp.sdc.common.config.EcompErrorEnum.AlarmSeverity; import org.openecomp.sdc.common.config.EcompErrorEnum.ErrorType; import org.openecomp.sdc.common.config.EcompErrorLogUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileWriter; @@ -35,198 +33,199 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class GenerateEcompErrorsCsv { - private static final Logger LOGGER = LoggerFactory.getLogger(GenerateEcompErrorsCsv.class); - - private static final String DATE_FORMAT = "dd-M-yyyy-hh-mm-ss"; + private static Logger log = LoggerFactory.getLogger(GenerateEcompErrorsCsv.class); + private static String DATE_FORMAT = "dd-M-yyyy-hh-mm-ss"; - private static final String NEW_LINE = System.getProperty("line.separator"); + private static String NEW_LINE = System.getProperty("line.separator"); - private static void usage() { - System.out.println("java org.openecomp.sdc.common.config.generation.GenerateEcompErrorsCsv "); - System.exit(1); - } + private static void usage() { + System.out.println("java org.openecomp.sdc.common.config.generation.GenerateEcompErrorsCsv "); + System.exit(1); + } - public static void main(String[] args) { + public static void main(String[] args) { - String targetFolder = "target"; - if (args.length > 1) { - targetFolder = args[0]; - } + String targetFolder = "target"; + if (args.length > 1) { + targetFolder = args[0]; + } - GenerateEcompErrorsCsv ecompErrorsCsv = new GenerateEcompErrorsCsv(); + GenerateEcompErrorsCsv ecompErrorsCsv = new GenerateEcompErrorsCsv(); - ecompErrorsCsv.generateEcompErrorsCsvFile(targetFolder, true); - } + ecompErrorsCsv.generateEcompErrorsCsvFile(targetFolder, true); + } - public static class EcompErrorRow { + public static class EcompErrorRow { - private String errorName; - private String errorCode; - private String description; - private ErrorType errorType; - private AlarmSeverity alarmSeverity; - private String cleanErrorCode; - private String resolution; + String errorName; + String errorCode; + String description; + ErrorType errorType; + AlarmSeverity alarmSeverity; + String cleanErrorCode; + String resolution; - public String getErrorName() { - return errorName; - } + public String getErrorName() { + return errorName; + } - public void setErrorName(String errorName) { - this.errorName = errorName; - } + public void setErrorName(String errorName) { + this.errorName = errorName; + } - public String getErrorCode() { - return errorCode; - } + public String getErrorCode() { + return errorCode; + } - public void setErrorCode(String errorCode) { - this.errorCode = errorCode; - } + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public ErrorType getErrorType() { - return errorType; - } + public ErrorType getErrorType() { + return errorType; + } - public void setErrorType(ErrorType errorType) { - this.errorType = errorType; - } + public void setErrorType(ErrorType errorType) { + this.errorType = errorType; + } - public AlarmSeverity getAlarmSeverity() { - return alarmSeverity; - } + public AlarmSeverity getAlarmSeverity() { + return alarmSeverity; + } - public void setAlarmSeverity(AlarmSeverity alarmSeverity) { - this.alarmSeverity = alarmSeverity; - } + public void setAlarmSeverity(AlarmSeverity alarmSeverity) { + this.alarmSeverity = alarmSeverity; + } - public String getCleanErrorCode() { - return cleanErrorCode; - } + public String getCleanErrorCode() { + return cleanErrorCode; + } - public void setCleanErrorCode(String cleanErrorCode) { - this.cleanErrorCode = cleanErrorCode; - } + public void setCleanErrorCode(String cleanErrorCode) { + this.cleanErrorCode = cleanErrorCode; + } - public String getResolution() { - return resolution; - } + public String getResolution() { + return resolution; + } - public void setResolution(String resolution) { - this.resolution = resolution; - } + public void setResolution(String resolution) { + this.resolution = resolution; + } - } + } - public boolean generateEcompErrorsCsvFile(String targetFolder, boolean addTimeToFileName) { + public boolean generateEcompErrorsCsvFile(String targetFolder, boolean addTimeToFileName) { - targetFolder += File.separator; + targetFolder += File.separator; - boolean result = false; - String dateFormatted = ""; + boolean result = false; + String dateFormatted = ""; - if (addTimeToFileName) { - DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); + if (addTimeToFileName) { + DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); - Date date = new Date(); + Date date = new Date(); - dateFormatted = "." + dateFormat.format(date); + dateFormatted = "." + dateFormat.format(date); - } + } - String outputFile = targetFolder + "ecompErrorCodes" + dateFormatted + ".csv"; + String outputFile = targetFolder + "ecompErrorCodes" + dateFormatted + ".csv"; - try (FileWriter writer = new FileWriter(outputFile)) { + try(FileWriter writer = new FileWriter(outputFile)) { - List errors = new ArrayList<>(); + List errors = new ArrayList<>(); - for (EcompErrorEnum ecompErrorEnum : EcompErrorEnum.values()) { + for (EcompErrorEnum ecompErrorEnum : EcompErrorEnum.values()) { - EcompErrorRow ecompErrorRow = new EcompErrorRow(); + EcompErrorRow ecompErrorRow = new EcompErrorRow(); - String errorCode = EcompErrorLogUtil.createEcode(ecompErrorEnum); + String errorCode = EcompErrorLogUtil.createEcode(ecompErrorEnum); - EcompErrorEnum clearCodeEnum = ecompErrorEnum.getClearCode(); - String cleanErrorCode = null; - if (clearCodeEnum != null) { - cleanErrorCode = EcompErrorLogUtil.createEcode(clearCodeEnum); - } + EcompErrorEnum clearCodeEnum = ecompErrorEnum.getClearCode(); + String cleanErrorCode = null; + if (clearCodeEnum != null) { + cleanErrorCode = EcompErrorLogUtil.createEcode(clearCodeEnum); + } - ecompErrorRow.setAlarmSeverity(ecompErrorEnum.getAlarmSeverity()); - ecompErrorRow.setCleanErrorCode(cleanErrorCode); - ecompErrorRow.setDescription(ecompErrorEnum.getEcompErrorCode().getDescription()); - ecompErrorRow.setErrorCode(errorCode); - ecompErrorRow.setErrorName(ecompErrorEnum.name().toString()); - ecompErrorRow.setErrorType(ecompErrorEnum.geteType()); - ecompErrorRow.setResolution(ecompErrorEnum.getEcompErrorCode().getResolution()); + ecompErrorRow.setAlarmSeverity(ecompErrorEnum.getAlarmSeverity()); + ecompErrorRow.setCleanErrorCode(cleanErrorCode); + ecompErrorRow.setDescription(ecompErrorEnum.getEcompErrorCode().getDescription()); + ecompErrorRow.setErrorCode(errorCode); + ecompErrorRow.setErrorName(ecompErrorEnum.name().toString()); + ecompErrorRow.setErrorType(ecompErrorEnum.geteType()); + ecompErrorRow.setResolution(ecompErrorEnum.getEcompErrorCode().getResolution()); - errors.add(ecompErrorRow); - } + errors.add(ecompErrorRow); + } - writeHeaders(writer); + writeHeaders(writer); - for (EcompErrorRow ecompErrorRow : errors) { - writer.append(addInvertedCommas(ecompErrorRow.getErrorCode())); - writer.append(','); - writer.append(addInvertedCommas(ecompErrorRow.getErrorType().toString())); - writer.append(','); - writer.append(addInvertedCommas(ecompErrorRow.getDescription())); - writer.append(','); - writer.append(addInvertedCommas(ecompErrorRow.getResolution())); - writer.append(','); - writer.append(addInvertedCommas(ecompErrorRow.getAlarmSeverity().toString())); - writer.append(','); - writer.append(addInvertedCommas(ecompErrorRow.getErrorName())); - writer.append(','); - writer.append(addInvertedCommas(ecompErrorRow.getCleanErrorCode())); - writer.append(NEW_LINE); - } + for (EcompErrorRow ecompErrorRow : errors) { + writer.append(addInvertedCommas(ecompErrorRow.getErrorCode())); + writer.append(','); + writer.append(addInvertedCommas(ecompErrorRow.getErrorType().toString())); + writer.append(','); + writer.append(addInvertedCommas(ecompErrorRow.getDescription())); + writer.append(','); + writer.append(addInvertedCommas(ecompErrorRow.getResolution())); + writer.append(','); + writer.append(addInvertedCommas(ecompErrorRow.getAlarmSeverity().toString())); + writer.append(','); + writer.append(addInvertedCommas(ecompErrorRow.getErrorName())); + writer.append(','); + writer.append(addInvertedCommas(ecompErrorRow.getCleanErrorCode())); + writer.append(NEW_LINE); + } - result = true; + result = true; - } catch (Exception e) { - LOGGER.info("generate Ecomp Errors Csv File failed - {}", e); - } + } catch (Exception e) { + log.info("generate Ecomp Errors Csv File failed - {}" , e); + } - return result; - } + return result; + } - private void writeHeaders(FileWriter writer) throws IOException { + private void writeHeaders(FileWriter writer) throws IOException { - writer.append("\"ERROR CODE\""); - writer.append(','); - writer.append("\"ERROR TYPE\""); - writer.append(','); - writer.append("\"DESCRIPTION\""); - writer.append(','); - writer.append("\"RESOLUTION\""); - writer.append(','); - writer.append("\"ALARM SEVERITY\""); - writer.append(','); - writer.append("\"ERROR NAME\""); - writer.append(','); - writer.append("\"CLEAN CODE\""); - writer.append(NEW_LINE); - } + writer.append("\"ERROR CODE\""); + writer.append(','); + writer.append("\"ERROR TYPE\""); + writer.append(','); + writer.append("\"DESCRIPTION\""); + writer.append(','); + writer.append("\"RESOLUTION\""); + writer.append(','); + writer.append("\"ALARM SEVERITY\""); + writer.append(','); + writer.append("\"ERROR NAME\""); + writer.append(','); + writer.append("\"CLEAN CODE\""); + writer.append(NEW_LINE); + } - private String addInvertedCommas(String str) { + private String addInvertedCommas(String str) { - if (str == null) { - return "\"\""; - } + if (str == null) { + return "\"\""; + } - return "\"" + str + "\""; - } + return "\"" + str + "\""; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKey.java b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKey.java index 57752ae420..06b2452d82 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKey.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKey.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,92 +23,92 @@ package org.openecomp.sdc.common.datastructure; import java.util.Date; public enum AuditingFieldsKey { - // General - AUDIT_TIMESTAMP(Date.class, "TIMESTAMP"), - AUDIT_ACTION(String.class, "ACTION"), - AUDIT_MODIFIER_NAME(String.class, "MODIFIER_ID"), - AUDIT_MODIFIER_UID(String.class, "MODIFIER"), - AUDIT_STATUS(String.class, "STATUS"), - AUDIT_DESC(String.class, "DESC"), - AUDIT_SERVICE_INSTANCE_ID(String.class, "SERVICE_INSTANCE_ID"), - AUDIT_INVARIANT_UUID(String.class, "INVARIANT_UUID"), - AUDIT_REQUEST_ID(String.class, "REQUEST_ID"), + // General + AUDIT_TIMESTAMP(Date.class, "TIMESTAMP"), + AUDIT_ACTION(String.class, "ACTION"), + AUDIT_MODIFIER_NAME(String.class, "MODIFIER_ID"), + AUDIT_MODIFIER_UID(String.class, "MODIFIER"), + AUDIT_STATUS(String.class, "STATUS"), + AUDIT_DESC(String.class, "DESC"), + AUDIT_SERVICE_INSTANCE_ID(String.class, "SERVICE_INSTANCE_ID"), + AUDIT_INVARIANT_UUID(String.class, "INVARIANT_UUID"), + AUDIT_REQUEST_ID(String.class, "REQUEST_ID"), - // Users administration - AUDIT_USER_UID(String.class, "USER"), - AUDIT_USER_BEFORE(String.class, "USER_BEFORE"), - AUDIT_USER_AFTER(String.class, "USER_AFTER"), - AUDIT_USER_DETAILS(String.class, "DETAILS"), + // Users administration + AUDIT_USER_UID(String.class, "USER"), + AUDIT_USER_BEFORE(String.class, "USER_BEFORE"), + AUDIT_USER_AFTER(String.class, "USER_AFTER"), + AUDIT_USER_DETAILS(String.class, "DETAILS"), - // Resource administration - AUDIT_RESOURCE_NAME(String.class, "RESOURCE_NAME"), - AUDIT_RESOURCE_TYPE(String.class, "RESOURCE_TYPE"), - AUDIT_RESOURCE_CURR_VERSION(String.class, "CURR_VERSION"), - AUDIT_RESOURCE_PREV_VERSION(String.class, "PREV_VERSION"), - AUDIT_RESOURCE_CURR_STATE(String.class, "CURR_STATE"), - AUDIT_RESOURCE_PREV_STATE(String.class, "PREV_STATE"), - AUDIT_RESOURCE_COMMENT(String.class, "COMMENT"), - AUDIT_ARTIFACT_DATA(String.class, "ARTIFACT_DATA"), - AUDIT_PREV_ARTIFACT_UUID(String.class, "PREV_ARTIFACT_UUID"), - AUDIT_CURR_ARTIFACT_UUID(String.class, "CURR_ARTIFACT_UUID"), - AUDIT_RESOURCE_DPREV_STATUS(String.class, "DPREV_STATUS"), - AUDIT_RESOURCE_DCURR_STATUS(String.class, "DCURR_STATUS"), - AUDIT_RESOURCE_TOSCA_NODE_TYPE(String.class, "TOSCA_NODE_TYPE"), - AUDIT_RESOURCE_URL(String.class, "RESOURCE_URL"), + // Resource administration + AUDIT_RESOURCE_NAME(String.class, "RESOURCE_NAME"), + AUDIT_RESOURCE_TYPE(String.class, "RESOURCE_TYPE"), + AUDIT_RESOURCE_CURR_VERSION(String.class, "CURR_VERSION"), + AUDIT_RESOURCE_PREV_VERSION(String.class, "PREV_VERSION"), + AUDIT_RESOURCE_CURR_STATE(String.class, "CURR_STATE"), + AUDIT_RESOURCE_PREV_STATE(String.class, "PREV_STATE"), + AUDIT_RESOURCE_COMMENT(String.class, "COMMENT"), + AUDIT_ARTIFACT_DATA(String.class, "ARTIFACT_DATA"), + AUDIT_PREV_ARTIFACT_UUID(String.class, "PREV_ARTIFACT_UUID"), + AUDIT_CURR_ARTIFACT_UUID(String.class, "CURR_ARTIFACT_UUID"), + AUDIT_RESOURCE_DPREV_STATUS(String.class, "DPREV_STATUS"), + AUDIT_RESOURCE_DCURR_STATUS(String.class, "DCURR_STATUS"), + AUDIT_RESOURCE_TOSCA_NODE_TYPE(String.class, "TOSCA_NODE_TYPE"), + AUDIT_RESOURCE_URL(String.class, "RESOURCE_URL"), - // Distribution Engine - AUDIT_DISTRIBUTION_ENVRIONMENT_NAME(String.class, "D_ENV"), - AUDIT_DISTRIBUTION_TOPIC_NAME(String.class, "TOPIC_NAME"), - AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME(String.class, "DNOTIF_TOPIC"), + // Distribution Engine + AUDIT_DISTRIBUTION_ENVRIONMENT_NAME(String.class, "D_ENV"), + AUDIT_DISTRIBUTION_TOPIC_NAME(String.class, "TOPIC_NAME"), + AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME(String.class, "DNOTIF_TOPIC"), AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME(String.class, "DSTATUS_TOPIC"), - AUDIT_DISTRIBUTION_ROLE(String.class, "ROLE"), - AUDIT_DISTRIBUTION_ID(String.class, "DID"), - AUDIT_DISTRIBUTION_API_KEY(String.class, "API_KEY"), - AUDIT_DISTRIBUTION_CONSUMER_ID(String.class, "CONSUMER_ID"), - AUDIT_DISTRIBUTION_RESOURCE_URL(String.class, "RESOURCE_URL"), - AUDIT_DISTRIBUTION_STATUS_TIME(String.class, "STATUS_TIME"), + AUDIT_DISTRIBUTION_ROLE(String.class, "ROLE"), + AUDIT_DISTRIBUTION_ID(String.class, "DID"), + AUDIT_DISTRIBUTION_API_KEY(String.class, "API_KEY"), + AUDIT_DISTRIBUTION_CONSUMER_ID(String.class, "CONSUMER_ID"), + AUDIT_DISTRIBUTION_RESOURCE_URL(String.class, "RESOURCE_URL"), + AUDIT_DISTRIBUTION_STATUS_TIME(String.class, "STATUS_TIME"), AUDIT_DISTRIBUTION_STATUS_DESC(String.class, "STATUS_DESC"), - AUDIT_DISTRIBUTION_ENVIRONMENT_ID(String.class, "ENV_ID"), - AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT(String.class, "VNF_WORKLOAD_CONTEXT"), - AUDIT_DISTRIBUTION_TENANT(String.class, "TENANT"), + AUDIT_DISTRIBUTION_ENVIRONMENT_ID(String.class, "ENV_ID"), + AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT(String.class, "VNF_WORKLOAD_CONTEXT"), + AUDIT_DISTRIBUTION_TENANT(String.class, "TENANT"), - // category - AUDIT_CATEGORY_NAME(String.class, "CATEGORY_NAME"), - AUDIT_SUB_CATEGORY_NAME(String.class, "SUB_CATEGORY_NAME"), - AUDIT_GROUPING_NAME(String.class, "GROUPING_NAME"), - AUDIT_DETAILS(String.class, "DETAILS"), + // category + AUDIT_CATEGORY_NAME(String.class, "CATEGORY_NAME"), + AUDIT_SUB_CATEGORY_NAME(String.class, "SUB_CATEGORY_NAME"), + AUDIT_GROUPING_NAME(String.class, "GROUPING_NAME"), + AUDIT_DETAILS(String.class, "DETAILS"), - //operational environment - AUDIT_OPERATIONAL_ENVIRONMENT_ID(String.class, "OPERATIONAL_ENVIRONMENT_ID"), - AUDIT_OPERATIONAL_ENVIRONMENT_NAME(String.class, "OPERATIONAL_ENVIRONMENT_NAME"), - AUDIT_OPERATIONAL_ENVIRONMENT_TYPE(String.class, "OPERATIONAL_ENVIRONMENT_TYPE"), - AUDIT_OPERATIONAL_ENVIRONMENT_ACTION(String.class, "OPERATIONAL_ENVIRONMENT_ACTION"), - AUDIT_TENANT_CONTEXT(String.class, "TENANT_CONTEXT"), + //operational environment + AUDIT_OPERATIONAL_ENVIRONMENT_ID(String.class, "OPERATIONAL_ENVIRONMENT_ID"), + AUDIT_OPERATIONAL_ENVIRONMENT_NAME(String.class, "OPERATIONAL_ENVIRONMENT_NAME"), + AUDIT_OPERATIONAL_ENVIRONMENT_TYPE(String.class, "OPERATIONAL_ENVIRONMENT_TYPE"), + AUDIT_OPERATIONAL_ENVIRONMENT_ACTION(String.class, "OPERATIONAL_ENVIRONMENT_ACTION"), + AUDIT_TENANT_CONTEXT(String.class, "TENANT_CONTEXT"), - // authentication - AUDIT_AUTH_URL(String.class, "URL"), - AUDIT_AUTH_USER(String.class, "USER"), - AUDIT_AUTH_STATUS(String.class, "AUTH_STATUS"), - AUDIT_AUTH_REALM(String.class, "REALM"), - AUDIT_ECOMP_USER(String.class, "ECOMP_USER"); + // authentication + AUDIT_AUTH_URL(String.class, "URL"), + AUDIT_AUTH_USER(String.class, "USER"), + AUDIT_AUTH_STATUS(String.class, "AUTH_STATUS"), + AUDIT_AUTH_REALM(String.class, "REALM"), + AUDIT_ECOMP_USER(String.class, "ECOMP_USER"); - private Class clazz; - private String displayName; + private Class clazz; + private String displayName; - AuditingFieldsKey(Class clazz, String displayName) { - this.clazz = clazz; - this.displayName = displayName; - } + AuditingFieldsKey(Class clazz, String displayName) { + this.clazz = clazz; + this.displayName = displayName; + } - public Class getValueClass() { - return this.clazz; - } + public Class getValueClass() { + return this.clazz; + } - public String getDisplayName() { - return displayName; - } + public String getDisplayName() { + return displayName; + } - public void setDisplayName(String displayName) { - this.displayName = displayName; - } + public void setDisplayName(String displayName) { + this.displayName = displayName; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/ESTimeBasedEvent.java b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/ESTimeBasedEvent.java deleted file mode 100644 index 9e991e8dcb..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/ESTimeBasedEvent.java +++ /dev/null @@ -1,132 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.datastructure; - -import org.codehaus.jettison.json.JSONException; -import org.codehaus.jettison.json.JSONObject; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Formatter; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import java.util.TimeZone; - -/** - * Extending this class enforces the objects of implementing classes to have a - * timestamp, so that like in logstash, we can derive the index name for those - * object from the timestamp. - * - * @author paharoni - */ -public class ESTimeBasedEvent { - - private static final int TIMESTAMP_YEAR_SUBSTRING = 4; - private static final int TIMESTAMP_MONTH_SUBSTRING = 7; - private static final int TIMESTAMP_DAY_SUBSTRING = 10; - private static final int TIMESTAMP_HOURS_START = 11; - private static final int TIMESTAMP_HOURS_END = 13; - private static final int TIMESTAMP_MINUTES_START = 14; - private static final int TIMESTAMP_MINUTES_END = 16; - - protected SimpleDateFormat simpleDateFormat; - protected static String dateFormatPattern = "yyyy-MM-dd HH:mm:ss.SSS z"; - protected String timestamp; - protected Map fields = new HashMap<>(); - - public ESTimeBasedEvent() { - simpleDateFormat = new SimpleDateFormat(dateFormatPattern); - simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - this.timestamp = simpleDateFormat.format(new Date()); - fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), this.timestamp); - - } - - public static ESTimeBasedEvent createEventFromJson(String jsonString) throws JSONException { - - ESTimeBasedEvent event = new ESTimeBasedEvent(); - JSONObject gsonObj; - gsonObj = new JSONObject(jsonString); - Iterator keys = gsonObj.keys(); - - while (keys.hasNext()) { - String key = (String) keys.next(); - event.fields.put(key, gsonObj.get(key)); - if (key.equals(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName())) { - event.timestamp = (String) gsonObj.get(key); - } - } - return event; - } - - public String calculateYearIndexSuffix() { - return timestamp.substring(0, TIMESTAMP_YEAR_SUBSTRING); - } - - public String calculateMonthIndexSuffix() { - return timestamp.substring(0, TIMESTAMP_MONTH_SUBSTRING); - } - - public String calculateDayIndexSuffix() { - return timestamp.substring(0, TIMESTAMP_DAY_SUBSTRING); - } - - public String calculateHourIndexSuffix() { - return calculateBaseIndexSuffix().toString(); - } - - public String calculateMinuteIndexSuffix() { - return calculateBaseIndexSuffix().append("-").append(timestamp, TIMESTAMP_MINUTES_START, TIMESTAMP_MINUTES_END).toString(); - } - - private StringBuilder calculateBaseIndexSuffix() { - return new StringBuilder().append(timestamp, 0, TIMESTAMP_DAY_SUBSTRING).append("-").append(timestamp, TIMESTAMP_HOURS_START, TIMESTAMP_HOURS_END); - } - - protected String getFormattedString(String template, Object... params) { - String res; - StringBuilder sb = new StringBuilder(); - try (Formatter formatter = new Formatter(sb, Locale.US)) { - formatter.format(template, params); - res = formatter.toString(); - } - return res; - } - - public String getTimestamp() { - return timestamp; - } - - public void setTimestamp(String timestamp) { - this.timestamp = timestamp; - } - - public Map getFields() { - return fields; - } - - public void setFields(Map fields) { - this.fields = fields; - } - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java index 5d268d2948..7cd099e07e 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,97 +20,100 @@ package org.openecomp.sdc.common.datastructure; -import fj.F; -import fj.data.Either; -import org.apache.commons.lang3.math.NumberUtils; -import org.openecomp.sdc.common.log.wrappers.Logger; +import static org.apache.commons.lang3.StringUtils.EMPTY; import java.io.Serializable; import java.util.Arrays; import java.util.List; import java.util.Optional; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; +import java.util.concurrent.*; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; +import org.apache.commons.lang3.math.NumberUtils; +import org.apache.commons.lang3.time.StopWatch; +import org.openecomp.sdc.common.log.enums.EcompErrorSeverity; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import fj.F; +import fj.data.Either; + /** * Class For Functional interfaces And Functional Methods - * + * * @author mshitrit + * */ public class FunctionalInterfaces { - private static final int DEFAULT_REDO_INTERVAL_TIME_MS = 50; - private static final int DEFAULT_MAX_WAIT_TIME_MS = 10000; - private static final Logger LOGGER = Logger.getLogger(FunctionalInterfaces.class.getName()); - - /** - * This is an interface of a List that implements Serializable - * - * @param - * @author mshitrit - */ - public interface SerializableList extends List, Serializable { - } - - /** - * @param - * @param - * @author mshitrit Consumer that takes two parameters - */ - public interface ConsumerTwoParam { - /** - * Same Accept method, but takes two parameters - * - * @param t1 - * @param t2 - */ - void accept(T1 t1, T2 t2); - } - - /** - * @param - * @param - * @param - * @author mshitrit Function that takes two parameters - */ - public interface FunctionTwoParam { - /** - * Same apply method, but takes two parameters - * - * @param t1 - * @param t2 - * @return - */ - R apply(T1 t1, T2 t2); - } - - /** - * @param - * @param - * @param - * @author mshitrit Function that throws an exception - */ - public interface FunctionThrows { - /** - * Same apply method, but throws an exception - * - * @param t - * @return - */ - R apply(T t) throws E; - } + private static final int DEFAULT_REDO_INTERVAL_TIME_MS = 50; + private static final int DEFAULT_MAX_WAIT_TIME_MS = 10000; + private static final Logger LOGGER = Logger.getLogger(FunctionalInterfaces.class.getName()); + + /** + * This is an interface of a List that implements Serializable + * + * @author mshitrit + * + * @param + */ + public interface SerializableList extends List, Serializable { + } + + /** + * @author mshitrit Consumer that takes two parameters + * @param + * @param + */ + public interface ConsumerTwoParam { + /** + * Same Accept method, but takes two parameters + * + * @param t1 + * @param t2 + */ + void accept(T1 t1, T2 t2); + } + + /** + * @author mshitrit Function that takes two parameters + * @param + * @param + * @param + */ + public interface FunctionTwoParam { + /** + * Same apply method, but takes two parameters + * + * @param t1 + * @param t2 + * @return + */ + R apply(T1 t1, T2 t2); + } + + /** + * @author mshitrit Function that throws an exception + * @param + * @param + * @param + */ + public interface FunctionThrows { + /** + * Same apply method, but throws an exception + * + * @param t + * @return + */ + R apply(T t) throws E; + } public interface FunctionTwoParamThrows { /** * Same apply method, but throws an exception - * + * * @param t1 * @param t2 * @return @@ -118,213 +121,219 @@ public class FunctionalInterfaces { R apply(T1 t1, T2 t2) throws E; } - /** - * @param - * @param - * @author mshitrit Supplier that throws an exception - */ - public interface SupplierThrows { - /** - * Same get method, but throws an exception - * - * @return - * @throws E - */ - R get() throws E; - } - - /** - * @param - * @param - * @author mshitrit Consumer that throws an exception - */ - public interface ConsumerThrows { - /** - * Same accept, but throws an exception - * - * @param t - * @throws E - */ - void accept(T t) throws E; - } - - /** - * @param - * @author mshitrit Runnable that throws an exception - */ - public interface RunnableThrows { - /** - * Same run, but throws an exception - * - * @throws E - */ - void run() throws E; - } - - /** - * Runs a method that declares throwing an Exception and has a return value. - *
    - * In case Exception Occurred replaces it with FunctionalAttException.
    - * This is useful for two cases:
    - * 1.using methods that throws exceptions in streams.
    - * 2.replacing declared exception with undeclared exception (Runtime).
    - * See below Use Case:
    - * Instead of: intList.stream().map(e -> fooThrowsAndReturnsBoolean(e)); - - * does not compile !
    - * Use This : intList.stream().map(e -> swallowException( () -> - * fooThrowsAndReturnsBoolean(e))); - compiles !
    - * - * @param methodToRun - * @return - */ - public static R swallowException(SupplierThrows methodToRun) { - try { + /** + * @author mshitrit Supplier that throws an exception + * @param + * @param + */ + public interface SupplierThrows { + /** + * Same get method, but throws an exception + * + * @return + * @throws E + */ + R get() throws E; + } + + /** + * @author mshitrit Consumer that throws an exception + * @param + * @param + */ + public interface ConsumerThrows { + /** + * Same accept, but throws an exception + * + * @param t + * @throws E + */ + void accept(T t) throws E; + } + + /** + * @author mshitrit Runnable that throws an exception + * @param + */ + public interface RunnableThrows { + /** + * Same run, but throws an exception + * + * @throws E + */ + void run() throws E; + } + + /** + * Runs a method that declares throwing an Exception and has a return value. + *
    + * In case Exception Occurred replaces it with FunctionalAttException.
    + * This is useful for two cases:
    + * 1.using methods that throws exceptions in streams.
    + * 2.replacing declared exception with undeclared exception (Runtime).
    + * See below Use Case:
    + * Instead of: intList.stream().map(e -> fooThrowsAndReturnsBoolean(e)); - + * does not compile !
    + * Use This : intList.stream().map(e -> swallowException( () -> + * fooThrowsAndReturnsBoolean(e))); - compiles !
    + * + * @param methodToRun + * @return + */ + public static R swallowException(SupplierThrows methodToRun) { + try { return methodToRun.get(); - } catch (Exception e) { - throw new FunctionalAttException(e); - } - } - - /** - * Runs a method that declares throwing an Exception without return value. - *
    - * In case Exception Occurred replaces it with FunctionalAttException.
    - * This is useful for two cases:
    - * 1.using methods that throws exceptions in streams.
    - * 2.replacing declared exception with undeclared exception (Runtime).
    - * See below Use Case:
    - * - * @param methodToRun - */ - public static void swallowException(RunnableThrows methodToRun) { - - SupplierThrows runnableWrapper = () -> { - methodToRun.run(); - return true; - }; - swallowException(runnableWrapper); - } - - private static class FunctionalAttException extends RuntimeException { - private static final long serialVersionUID = 1L; - - private FunctionalAttException(Exception e) { - super(e); - } - } - - /** - * Runs the given method.
    - * Verify the method result against the resultVerifier.
    - * If verification passed returns the result.
    - * If Verification failed keeps retrying until it passes or until 10 seconds - * pass.
    - * If Exception Occurred keeps retrying until it passes or until 10 seconds - * pass,
    - * If last retry result caused an exception - it is thrown. - * - * @param methodToRun given Method - * @param resultVerifier verifier for the method result - * @return - */ - public static R retryMethodOnResult(Supplier methodToRun, Function resultVerifier) { - return retryMethodOnResult(methodToRun, resultVerifier, DEFAULT_MAX_WAIT_TIME_MS, - DEFAULT_REDO_INTERVAL_TIME_MS); - } - - /** - * Runs the given method.
    - * Verify the method result against the resultVerifier.
    - * If verification passed returns the result.
    - * If Verification failed keeps retrying until it passes or until maxWait - * pass.
    - * If Exception Occurred keeps retrying until it passes or until maxWait - * pass,
    - * If last retry result caused an exception - it is thrown. - * - * @param methodToRun given Method - * @param resultVerifier verifier for the method result - * @param maxWaitMS - * @param retryIntervalMS - * @return - */ - public static R retryMethodOnResult(Supplier methodToRun, Function resultVerifier, - long maxWaitMS, long retryIntervalMS) { - boolean stopSearch = false; - R ret = null; - int timeElapsed = 0; - FunctionalAttException functionalExceotion = null; - boolean isExceptionInLastTry = false; - while (!stopSearch) { - try { - ret = methodToRun.get(); - stopSearch = resultVerifier.apply(ret); - isExceptionInLastTry = false; - } catch (Exception e) { - functionalExceotion = new FunctionalAttException(e); - isExceptionInLastTry = true; - - } finally { - sleep(retryIntervalMS); - timeElapsed += retryIntervalMS; - if (timeElapsed > maxWaitMS) { - stopSearch = true; - } - } - - } - if (isExceptionInLastTry) { - throw functionalExceotion; - } else { - return ret; - } - - } - - /** - * Runs the given method.
    - * Verify the method result against the resultVerifier.
    - * If verification passed returns the result.
    - * If Verification failed keeps retrying until maxRetries reached.
    - * If Exception Occurred keeps retrying until it passes or until maxRetries - * reached,
    - * If last retry result caused an exception - it is thrown. - * - * @param methodToRun given Method - * @param resultVerifier verifier for the method result - * @param maxRetries - * @return - */ - public static R retryMethodOnResult(Supplier methodToRun, Function resultVerifier, - long maxRetries) { - boolean stopSearch = false; - R ret = null; - int retriesCount = 0; - FunctionalAttException functionalExceotion = null; - boolean isExceptionInLastTry = false; - while (!stopSearch) { - try { - ret = methodToRun.get(); - stopSearch = resultVerifier.apply(ret); - isExceptionInLastTry = false; - } catch (Exception e) { - functionalExceotion = new FunctionalAttException(e); - isExceptionInLastTry = true; - } finally { - if (++retriesCount >= maxRetries) { - stopSearch = true; - } - } - } - if (isExceptionInLastTry) { - throw functionalExceotion; - } else { - return ret; - } - } - - public static R retryMethodOnException(SupplierThrows methodToRun, - Function exceptionVerifier, long maxRetries) throws Exception { + } catch (Exception e) { + throw new FunctionalAttException(e); + } + } + + /** + * Runs a method that declares throwing an Exception without return value. + *
    + * In case Exception Occurred replaces it with FunctionalAttException.
    + * This is useful for two cases:
    + * 1.using methods that throws exceptions in streams.
    + * 2.replacing declared exception with undeclared exception (Runtime).
    + * See below Use Case:
    + * + * @param methodToRun + */ + public static void swallowException(RunnableThrows methodToRun) { + + SupplierThrows runnableWrapper = () -> { + methodToRun.run(); + return true; + }; + swallowException(runnableWrapper); + } + + private static class FunctionalAttException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private FunctionalAttException(Exception e) { + super(e); + } + } + + /** + * Runs the given method.
    + * Verify the method result against the resultVerifier.
    + * If verification passed returns the result.
    + * If Verification failed keeps retrying until it passes or until 10 seconds + * pass.
    + * If Exception Occurred keeps retrying until it passes or until 10 seconds + * pass,
    + * If last retry result caused an exception - it is thrown. + * + * @param methodToRun + * given Method + * @param resultVerifier + * verifier for the method result + * @return + */ + public static R retryMethodOnResult(Supplier methodToRun, Function resultVerifier) { + return retryMethodOnResult(methodToRun, resultVerifier, DEFAULT_MAX_WAIT_TIME_MS, + DEFAULT_REDO_INTERVAL_TIME_MS); + } + + /** + * Runs the given method.
    + * Verify the method result against the resultVerifier.
    + * If verification passed returns the result.
    + * If Verification failed keeps retrying until it passes or until maxWait + * pass.
    + * If Exception Occurred keeps retrying until it passes or until maxWait + * pass,
    + * If last retry result caused an exception - it is thrown. + * + * @param methodToRun + * given Method + * @param resultVerifier + * verifier for the method result + * @param maxWaitMS + * @param retryIntervalMS + * @return + */ + public static R retryMethodOnResult(Supplier methodToRun, Function resultVerifier, + long maxWaitMS, long retryIntervalMS) { + boolean stopSearch = false; + R ret = null; + int timeElapsed = 0; + FunctionalAttException functionalExceotion = null; + boolean isExceptionInLastTry = false; + while (!stopSearch) { + try { + ret = methodToRun.get(); + stopSearch = resultVerifier.apply(ret); + isExceptionInLastTry = false; + } catch (Exception e) { + functionalExceotion = new FunctionalAttException(e); + isExceptionInLastTry = true; + + } finally { + sleep(retryIntervalMS); + timeElapsed += retryIntervalMS; + if (timeElapsed > maxWaitMS) { + stopSearch = true; + } + } + + } + if (isExceptionInLastTry) { + throw functionalExceotion; + } else { + return ret; + } + + } + + /** + * Runs the given method.
    + * Verify the method result against the resultVerifier.
    + * If verification passed returns the result.
    + * If Verification failed keeps retrying until maxRetries reached.
    + * If Exception Occurred keeps retrying until it passes or until maxRetries + * reached,
    + * If last retry result caused an exception - it is thrown. + * + * @param methodToRun + * given Method + * @param resultVerifier + * verifier for the method result + * @param maxRetries + * @return + */ + public static R retryMethodOnResult(Supplier methodToRun, Function resultVerifier, + long maxRetries) { + boolean stopSearch = false; + R ret = null; + int retriesCount = 0; + FunctionalAttException functionalExceotion = null; + boolean isExceptionInLastTry = false; + while (!stopSearch) { + try { + ret = methodToRun.get(); + stopSearch = resultVerifier.apply(ret); + isExceptionInLastTry = false; + } catch (Exception e) { + functionalExceotion = new FunctionalAttException(e); + isExceptionInLastTry = true; + } finally { + if (++retriesCount >= maxRetries) { + stopSearch = true; + } + } + } + if (isExceptionInLastTry) { + throw functionalExceotion; + } else { + return ret; + } + } + + public static R retryMethodOnException(SupplierThrows methodToRun, + Function exceptionVerifier, long maxRetries) throws Exception { boolean stopSearch = false; R ret = null; int retriesCount = 0; @@ -334,10 +343,12 @@ public class FunctionalInterfaces { exception = null; ret = methodToRun.get(); stopSearch = true; - } catch (Exception e) { + } + catch (Exception e) { exception = e; stopSearch = exceptionVerifier.apply(e); - } finally { + } + finally { if (++retriesCount >= maxRetries) { stopSearch = true; } @@ -345,157 +356,162 @@ public class FunctionalInterfaces { } if (exception != null) { throw exception; - } else { - return ret; } - } - - /** - * Runs the given method.
    - * In case exception occurred runs the method again either until succeed or - * until 10 seconds pass. - * - * @param methodToRun given method - * @return - */ - - public static R retryMethodOnException(Supplier methodToRun) { - Function dummyVerifier = someResult -> true; - return retryMethodOnResult(methodToRun, dummyVerifier, DEFAULT_MAX_WAIT_TIME_MS, DEFAULT_REDO_INTERVAL_TIME_MS); - } - - /** - * Runs the given method.
    - * In case exception occurred runs the method again either until succeed or - * until 10 seconds pass. - * - * @param methodToRun given method - */ - public static void retryMethodOnException(Runnable methodToRun) { - Function dummyVerifier = someResult -> true; - Supplier dummySupplier = () -> { - methodToRun.run(); - return true; - }; - retryMethodOnResult(dummySupplier, dummyVerifier, DEFAULT_MAX_WAIT_TIME_MS, DEFAULT_REDO_INTERVAL_TIME_MS); - } - - /** - * Same as Thread.sleep but throws a FunctionalAttException - * (RuntimeException) instead of InterruptedException.
    - * - * @param millis - */ - public static void sleep(long millis) { - swallowException(() -> Thread.sleep(millis)); - - } - - /** - * Converts Either containing right value to another either with different - * type of left value and the same type of right value. - * - * @param eitherToConvert - * @return - */ - public static Either convertEitherRight(Either eitherToConvert) { - if (eitherToConvert.isLeft()) { - throw new UnsupportedOperationException("Can not convert either right value because it has left value"); - } else { - return Either.right(eitherToConvert.right().value()); - } - - } - - /** - * Converts Either containing left value to another either with different - * type of right value and the same type of left value. - * - * @param eitherToConvert - * @return - */ - public static Either convertEitherLeft(Either eitherToConvert) { - if (eitherToConvert.isLeft()) { - throw new UnsupportedOperationException("Can not convert either left value because it has right value"); - } else { - return Either.left(eitherToConvert.left().value()); - } - - } - - /** - * Returns enum value for a field
    - * - * @param fieldValue - * @param values - * @param enumValueGetter - * @return - */ - public static > T getEnumValueByFieldValue(String fieldValue, T[] values, - Function enumValueGetter, T defaultValue) { - return getEnumValueByFieldValue(fieldValue, values, enumValueGetter, defaultValue, true); - - } - - - public static > T getEnumValueByFieldValue(String fieldValue, T[] values, - Function enumValueGetter, T defaultValue, boolean isCaseSensetive) { - - final Predicate predicate; - if (isCaseSensetive) { - predicate = e -> fieldValue.equals(enumValueGetter.apply(e)); - } else { - predicate = e -> fieldValue.equalsIgnoreCase(enumValueGetter.apply(e)); - } - Optional optionalFound = - // Stream of values of enum - Arrays.asList(values).stream(). - // Filter in the one that match the field - filter(predicate). - // collect - findAny(); - T ret; - ret = optionalFound.isPresent() ? optionalFound.get() : defaultValue; - return ret; - - } - - /** - * This method runs the given method.
    - * In case given method finished running within timeoutInMs limit it returns - * Either which left value is the result of the method that ran.
    - * In case given method did not finish running within timeoutInMs limit it - * returns Either which right value is false.
    - * - * @param supplier - * @param timeoutInMs - if 0 or lower no timeout is used - * @return - */ - public static Either runMethodWithTimeOut(Supplier supplier, long timeoutInMs) { - Either result; - if (timeoutInMs <= NumberUtils.LONG_ZERO) { - result = Either.left(supplier.get()); - } else { - ExecutorService pool = Executors.newSingleThreadExecutor(); - Future future = pool.submit(supplier::get); - try { - T calcValue = future.get(timeoutInMs, TimeUnit.MILLISECONDS); - result = Either.left(calcValue); - } catch (InterruptedException e) { - LOGGER.debug("InterruptedException in runMethodWithTimeOut", e); - Thread.currentThread().interrupt(); - result = Either.right(false); - } catch (ExecutionException | TimeoutException e) { - LOGGER.debug("method run was canceled because it has passed its time limit of {} MS", timeoutInMs, e); - result = Either.right(false); - } finally { - pool.shutdownNow(); - } + else { + return ret; } - return result; } - public static F convertToFunction(Consumer consumer) { + /** + * Runs the given method.
    + * In case exception occurred runs the method again either until succeed or + * until 10 seconds pass. + * + * @param methodToRun + * given method + * @return + */ + + public static R retryMethodOnException(Supplier methodToRun) { + Function dummyVerifier = someResult -> true; + return retryMethodOnResult(methodToRun, dummyVerifier, DEFAULT_MAX_WAIT_TIME_MS, DEFAULT_REDO_INTERVAL_TIME_MS); + } + + /** + * Runs the given method.
    + * In case exception occurred runs the method again either until succeed or + * until 10 seconds pass. + * + * @param methodToRun + * given method + */ + public static void retryMethodOnException(Runnable methodToRun) { + Function dummyVerifier = someResult -> true; + Supplier dummySupplier = () -> { + methodToRun.run(); + return true; + }; + retryMethodOnResult(dummySupplier, dummyVerifier, DEFAULT_MAX_WAIT_TIME_MS, DEFAULT_REDO_INTERVAL_TIME_MS); + } + + /** + * Same as Thread.sleep but throws a FunctionalAttException + * (RuntimeException) instead of InterruptedException.
    + * + * @param millis + */ + public static void sleep(long millis) { + swallowException(() -> Thread.sleep(millis)); + + } + + /** + * Converts Either containing right value to another either with different + * type of left value and the same type of right value. + * + * @param eitherToConvert + * @return + */ + public static Either convertEitherRight(Either eitherToConvert) { + if (eitherToConvert.isLeft()) { + throw new UnsupportedOperationException("Can not convert either right value because it has left value"); + } else { + return Either.right(eitherToConvert.right().value()); + } + + } + + /** + * Converts Either containing left value to another either with different + * type of right value and the same type of left value. + * + * @param eitherToConvert + * @return + */ + public static Either convertEitherLeft(Either eitherToConvert) { + if (eitherToConvert.isLeft()) { + throw new UnsupportedOperationException("Can not convert either left value because it has right value"); + } else { + return Either.left(eitherToConvert.left().value()); + } + + } + + /** + * Returns enum value for a field
    + * + * @param fieldValue + * @param values + * @param enumValueGetter + * @return + */ + public static > T getEnumValueByFieldValue(String fieldValue, T[] values, + Function enumValueGetter, T defaultValue) { + return getEnumValueByFieldValue(fieldValue, values, enumValueGetter, defaultValue, true); + + } + + + public static > T getEnumValueByFieldValue(String fieldValue, T[] values, + Function enumValueGetter, T defaultValue, boolean isCaseSensetive ){ + + final Predicate predicate; + if( isCaseSensetive ){ + predicate = e -> fieldValue.equals(enumValueGetter.apply(e)); + } + else{ + predicate = e -> fieldValue.equalsIgnoreCase(enumValueGetter.apply(e)); + } + Optional optionalFound = + // Stream of values of enum + Arrays.asList(values).stream(). + // Filter in the one that match the field + filter(predicate). + // collect + findAny(); + T ret; + ret = optionalFound.isPresent() ? optionalFound.get() : defaultValue; + return ret; + + } + + /** + * This method runs the given method.
    + * In case given method finished running within timeoutInMs limit it returns + * Either which left value is the result of the method that ran.
    + * In case given method did not finish running within timeoutInMs limit it + * returns Either which right value is false.
    + * + * @param supplier + * @param timeoutInMs + * - if 0 or lower no timeout is used + * @return + */ + public static Either runMethodWithTimeOut(Supplier supplier, long timeoutInMs) { + Either result; + if (timeoutInMs <= NumberUtils.LONG_ZERO) { + result = Either.left(supplier.get()); + } else { + ExecutorService pool = Executors.newSingleThreadExecutor(); + Future future = pool.submit(supplier::get); + try { + T calcValue = future.get(timeoutInMs, TimeUnit.MILLISECONDS); + result = Either.left(calcValue); + } catch (InterruptedException e) { + LOGGER.debug("InterruptedException in runMethodWithTimeOut", e); + Thread.currentThread().interrupt(); + result = Either.right(false); + } catch (ExecutionException | TimeoutException e) { + LOGGER.debug("method run was canceled because it has passed its time limit of {} MS", timeoutInMs, e); + result = Either.right(false); + } finally { + pool.shutdownNow(); + } + } + return result; + } + + public static F convertToFunction(Consumer consumer) { return t -> { try { consumer.accept(t); @@ -504,6 +520,83 @@ public class FunctionalInterfaces { return false; } }; - } + } + + /** + * Wraps the execution of the Runnable with try catch.
    + * In case exception occurred returns Optional containing the + * resultOnException.
    + * Otherwise returns an Empty optional. + * + * @param runnable + * @param resultOnException + * @return + */ + public static Optional wrapWithTryCatch(RunnableThrows runnable, + T resultOnException) { + Optional optionalError; + try { + runnable.run(); + optionalError = Optional.empty(); + } catch (Exception e) { + logException(e); + optionalError = Optional.of(resultOnException); + } + return optionalError; + } + + /** + * Runs the given method.
    + * In case the method passes without any Assertion Errors finishes.
    + * In case there is an assertion error keeps running the method every retryIntervalMS.
    until there is no Errors or maxWaitTimeMs has passed.
    + * If there are still Assertion Errors in the last Run they are returned to the user.
    + * + * @param methodToRun + * @param maxWaitTimeMs + * @param retryIntervalMS + */ + public static void retryMethodOnException (Runnable methodToRun, long maxWaitTimeMs, long retryIntervalMS) { + if (maxWaitTimeMs <= 0) { + throw new UnsupportedOperationException("Number maxWaitTimeMs be greater than 0"); + } + StopWatch watch = new StopWatch(); + watch.start(); + + boolean isLastTry = false; + while (!isLastTry) { + isLastTry = watch.getTime() + retryIntervalMS > maxWaitTimeMs; + if (isLastTry) { + methodToRun.run(); + } + else { + try { + methodToRun.run(); + break; + } catch (Exception e) { + wrapWithTryCatch(() -> Thread.sleep(retryIntervalMS)); + } + } + } + + + } + + /** + * Wraps the execution of the Runnable with try catch.
    + * In case exception occurred logs the Exception.
    + * resultOnException.
    + * Otherwise returns an Empty optional. + * + * @param runnable + * @return + */ + public static void wrapWithTryCatch(RunnableThrows runnable) { + wrapWithTryCatch(runnable, null); + } + + private static void logException(Exception e) { + LOGGER.error(EcompErrorSeverity.ERROR, EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, EMPTY, EMPTY, EMPTY, EMPTY); + LOGGER.debug("Error was caught ", e); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/MonitoringFieldsKeysEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/MonitoringFieldsKeysEnum.java index 4ac3e26f1e..f92b4ef687 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/MonitoringFieldsKeysEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/MonitoringFieldsKeysEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,35 +23,35 @@ package org.openecomp.sdc.common.datastructure; import java.util.Date; public enum MonitoringFieldsKeysEnum { - MONITORING_TIMESTAMP(Date.class, "TIMESTAMP"), - MONITORING_HOST_IP(String.class, "HOST_IP"), - MONITORING_HOST_CPU(Long.class, "HOST_CPU"), - MONITORING_HOST_MEM(Long.class, "HOST_MEMORY"), - MONITORING_HOST_DISC(Long.class, "HOST_DISC"), - MONITORING_JVM_ID(String.class, "JVM_ID"), - MONITORING_JVM_CPU(Long.class, "JVM_CPU"), - MONITORING_JVM_MEM(Long.class, "JVM_MEMORY"), - MONITORING_JVM_TNUM(Long.class, "JVM_TNUM"), - MONITORING_APP_ID(String.class, "APP_ID"), - MONITORING_APP_STAT(String.class, "APP_STAT"); - - private Class clazz; - private String displayName; - - MonitoringFieldsKeysEnum(Class clazz, String displayName) { - this.clazz = clazz; - this.displayName = displayName; - } - - public Class getValueClass() { - return this.clazz; - } - - public String getDisplayName() { - return displayName; - } - - public void setDisplayName(String displayName) { - this.displayName = displayName; - } + MONITORING_TIMESTAMP(Date.class, "TIMESTAMP"), + MONITORING_HOST_IP(String.class, "HOST_IP"), + MONITORING_HOST_CPU(Long.class, "HOST_CPU"), + MONITORING_HOST_MEM(Long.class, "HOST_MEMORY"), + MONITORING_HOST_DISC(Long.class, "HOST_DISC"), + MONITORING_JVM_ID(String.class, "JVM_ID"), + MONITORING_JVM_CPU(Long.class, "JVM_CPU"), + MONITORING_JVM_MEM(Long.class, "JVM_MEMORY"), + MONITORING_JVM_TNUM(Long.class, "JVM_TNUM"), + MONITORING_APP_ID(String.class, "APP_ID"), + MONITORING_APP_STAT(String.class, "APP_STAT"); + + private Class clazz; + private String displayName; + + MonitoringFieldsKeysEnum(Class clazz, String displayName) { + this.clazz = clazz; + this.displayName = displayName; + } + + public Class getValueClass() { + return this.clazz; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/UserContext.java b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/UserContext.java new file mode 100644 index 0000000000..8dcca6b6e1 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/UserContext.java @@ -0,0 +1,74 @@ +package org.openecomp.sdc.common.datastructure; + + +import java.util.Set; + +public class UserContext { + + + /** + * a pojo which holds the business logic layer to be aware of the user context as received in the authentication cookie + * Story https://jira.web.labs.att.com/browse/ASDC-232 + * Author: Idan Agam + */ + + + private String userId; + private String firstName; + private String lastName; + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + private Set userRoles; + + + public UserContext(String userId, Set userRoles, String firstName, String lastName) { + this.userId = userId; + this.userRoles = userRoles; + this.firstName = firstName; + this.lastName = lastName; + } + + public UserContext(String userId) { + this.userId = userId; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public Set getUserRoles() { + return userRoles; + } + + public void setUserRoles(Set userRoles) { + this.userRoles = userRoles; + } + + @Override + public String toString() { + return "UserContext{" + "userId='" + userId + '\'' + ", firstName='" + firstName + '\'' + ", lastname='" + lastName + '\'' + ", userRoles=" + userRoles + '}'; + } +} + + + + diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/Wrapper.java b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/Wrapper.java index 96c38cc3cf..43fd5ca15f 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/Wrapper.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/Wrapper.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,30 +22,31 @@ package org.openecomp.sdc.common.datastructure; /** * Very Basic Wrapper class. - * - * @param + * * @author mshitrit + * + * @param */ public class Wrapper { - private T innerElement; + private T innerElement; - public Wrapper(T innerElement) { - this.innerElement = innerElement; - } + public Wrapper(T innerElement) { + this.innerElement = innerElement; + } - public Wrapper() { - this.innerElement = null; - } + public Wrapper() { + this.innerElement = null; + } - public T getInnerElement() { - return innerElement; - } + public T getInnerElement() { + return innerElement; + } - public void setInnerElement(T innerElement) { - this.innerElement = innerElement; - } + public void setInnerElement(T innerElement) { + this.innerElement = innerElement; + } - public boolean isEmpty() { - return innerElement == null; - } + public boolean isEmpty() { + return innerElement == null; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java index 7273a04bd0..21c0f45e24 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,11 +19,10 @@ */ package org.openecomp.sdc.common.http.client.api; - import org.apache.http.client.HttpRequestRetryHandler; public interface ComparableHttpRequestRetryHandler extends HttpRequestRetryHandler { - default boolean compare(T handler) { + public default boolean compare(T handler) { return (handler != null && getClass() == handler.getClass()); } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java index 9ed3efde11..66a7050821 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,13 +29,7 @@ import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.AuthCache; import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPatch; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.client.methods.*; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicAuthCache; @@ -52,19 +46,17 @@ import java.net.URI; import java.util.Properties; public class HttpClient { - private static final Logger LOGGER = Logger.getLogger(HttpClient.class.getName()); - public static final int HTTPS_PORT = 443; - public static final int HTTP_PORT = 80; - + private static final Logger logger = Logger.getLogger(HttpClient.class.getName()); + private final CloseableHttpClient client; private final HttpClientConfigImmutable configImmutable; - - HttpClient(CloseableHttpClient client, HttpClientConfigImmutable configImmutable) { + + public HttpClient(CloseableHttpClient client, HttpClientConfigImmutable configImmutable) { this.client = client; - this.configImmutable = configImmutable; + this.configImmutable = configImmutable; } - - HttpResponse get(String url, Properties headers, FunctionThrows, Exception> responseBuilder) throws HttpExecuteException { + + public HttpResponse get(String url, Properties headers, FunctionThrows, Exception> responseBuilder) throws HttpExecuteException { HttpGet httpGet = new HttpGet(url); return execute(httpGet, headers, responseBuilder); } @@ -91,17 +83,18 @@ public class HttpClient { HttpDelete httpDelete = new HttpDelete(url); return execute(httpDelete, headers, responseBuilder); } - + void close() { try { client.close(); - } catch (IOException e) { - LOGGER.debug("Close http client failed with exception ", e); + } + catch (IOException e) { + logger.debug("Close http client failed with exception ", e); } } - + private HttpResponse execute(HttpRequestBase request, Properties headers, FunctionThrows, Exception> responseBuilder) throws HttpExecuteException { - if (configImmutable.getHeaders() != null) { + if(configImmutable.getHeaders() != null) { configImmutable.getHeaders().forEach(request::addHeader); } @@ -110,52 +103,57 @@ public class HttpClient { } HttpClientContext httpClientContext = null; - if (request.getHeaders(HttpHeaders.AUTHORIZATION).length == 0) { + if(request.getHeaders(HttpHeaders.AUTHORIZATION).length == 0) { httpClientContext = createHttpContext(request.getURI()); } - LOGGER.debug("Execute request {}", request.getRequestLine()); + logger.debug("Execute request {}", request.getRequestLine()); try (CloseableHttpResponse response = client.execute(request, httpClientContext)) { return responseBuilder.apply(response); - } catch (Exception e) { - String description = String.format("Execute request %s failed with exception: %s", request.getRequestLine(), e.getMessage()); + } + catch (Exception e) { + String description = String.format("Execute request %s failed with exception: %s", request.getRequestLine(), e.getMessage()); BeEcompErrorManager.getInstance().logInternalFlowError("ExecuteRestRequest", description, ErrorSeverity.ERROR); - LOGGER.debug("{}: ", description, e); + logger.debug("{}: ",description, e); throw new HttpExecuteException(description, e); - } + } } private HttpClientContext createHttpContext(URI uri) { - if (StringUtils.isEmpty(configImmutable.getBasicAuthUserName()) || StringUtils.isEmpty(configImmutable.getBasicAuthPassword())) { + if(StringUtils.isEmpty(configImmutable.getBasicAuthUserName()) || StringUtils.isEmpty(configImmutable.getBasicAuthPassword())) { return null; } CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); int port = getPort(uri); - credentialsProvider.setCredentials(new AuthScope(uri.getHost(), port), + credentialsProvider.setCredentials(new AuthScope(uri.getHost(), port), new UsernamePasswordCredentials(configImmutable.getBasicAuthUserName(), configImmutable.getBasicAuthPassword())); HttpClientContext localContext = HttpClientContext.create(); localContext.setCredentialsProvider(credentialsProvider); AuthCache authCache = new BasicAuthCache(); - authCache.put(new HttpHost(uri.getHost(), port), (AuthScheme) new BasicScheme()); + HttpHost target = new HttpHost(uri.getHost(), port, "https"); + authCache.put(target, (AuthScheme) new BasicScheme()); localContext.setAuthCache(authCache); return localContext; } private int getPort(URI uri) { - int port = uri.getPort(); - if (port < 0) { - if (Constants.HTTPS.equals(uri.getScheme())) { - port = HTTPS_PORT; - } else if (Constants.HTTP.equals(uri.getScheme())) { - port = HTTP_PORT; - } else { + int port = uri.getPort(); + if(port < 0) { + if(Constants.HTTPS.equals(uri.getScheme())) { + port = 443; + } + else + if (Constants.HTTP.equals(uri.getScheme())) { + port = 80; + } + else { port = AuthScope.ANY_PORT; - LOGGER.debug("Protocol \"{}\" is not supported, set port to {}", uri.getScheme(), port); + logger.debug("Protocol \"{}\" is not supported, set port to {}", uri.getScheme(), port); } } return port; diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java index f0fe09fe7c..9b21e1ac87 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,40 +29,46 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; -final class HttpClientConfigImmutable { +public final class HttpClientConfigImmutable { private final Map headers; private final BasicAuthorization basicAuthorization; private final ClientCertificate clientCertificate; private final Timeouts timeouts; + private boolean enableMetricLogging; /* - * use ComparableHttpRequestRetryHandler.compare instead of default generated equals + * use ComparableHttpRequestRetryHandler.compare instead of default generated equals */ private final ComparableHttpRequestRetryHandler retryHandler; private final int numOfRetries; - + static HttpClientConfigImmutable getOrCreate(HttpClientConfig httpClientConfig) { // TODO: retrieve from a pool if exist, otherwise create new - return new HttpClientConfigImmutable(httpClientConfig); + return new HttpClientConfigImmutable(httpClientConfig); } - HttpClientConfigImmutable(HttpClientConfig httpClientConfig) { + public HttpClientConfigImmutable(HttpClientConfig httpClientConfig) { timeouts = httpClientConfig.getTimeouts() != null ? new Timeouts(httpClientConfig.getTimeouts()) : null; basicAuthorization = httpClientConfig.getBasicAuthorization() != null ? new BasicAuthorization(httpClientConfig.getBasicAuthorization()) : null; clientCertificate = httpClientConfig.getClientCertificate() != null ? new ClientCertificate(httpClientConfig.getClientCertificate()) : null; headers = httpClientConfig.getHeaders() != null ? Collections.unmodifiableMap(new HashMap<>(httpClientConfig.getHeaders())) : null; retryHandler = httpClientConfig.getRetryHandler(); numOfRetries = httpClientConfig.getNumOfRetries(); + enableMetricLogging = httpClientConfig.isEnableMetricLogging(); + } + + public boolean isEnableMetricLogging() { + return enableMetricLogging; } Map getHeaders() { return headers; } - int getNumOfRetries() { + public int getNumOfRetries() { return numOfRetries; } - + String getBasicAuthPassword() { return basicAuthorization != null ? basicAuthorization.getPassword() : null; } @@ -82,20 +88,20 @@ final class HttpClientConfigImmutable { ClientCertificate getClientCertificate() { return clientCertificate != null ? new ClientCertificate(clientCertificate) : null; } - - int getReadTimeoutMs() { + + public int getReadTimeoutMs() { return timeouts.getReadTimeoutMs(); } - int getConnectTimeoutMs() { + public int getConnectTimeoutMs() { return timeouts.getConnectTimeoutMs(); } - int getConnectPoolTimeoutMs() { + public int getConnectPoolTimeoutMs() { return timeouts.getConnectPoolTimeoutMs(); } - ComparableHttpRequestRetryHandler getRetryHandler() { + public ComparableHttpRequestRetryHandler getRetryHandler() { return retryHandler; } @@ -113,51 +119,43 @@ final class HttpClientConfigImmutable { @Override public boolean equals(Object obj) { - if (this == obj) { + if (this == obj) return true; - } - if (obj == null) { + if (obj == null) return false; - } - if (getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) return false; - } HttpClientConfigImmutable other = (HttpClientConfigImmutable) obj; if (basicAuthorization == null) { - if (other.basicAuthorization != null) { + if (other.basicAuthorization != null) return false; - } - } else if (!basicAuthorization.equals(other.basicAuthorization)) { - return false; } + else if (!basicAuthorization.equals(other.basicAuthorization)) + return false; if (clientCertificate == null) { - if (other.clientCertificate != null) { + if (other.clientCertificate != null) return false; - } - } else if (!clientCertificate.equals(other.clientCertificate)) { - return false; } + else if (!clientCertificate.equals(other.clientCertificate)) + return false; if (headers == null) { - if (other.headers != null) { + if (other.headers != null) return false; - } - } else if (!headers.equals(other.headers)) { - return false; } + else if (!headers.equals(other.headers)) + return false; if (retryHandler == null) { - if (other.retryHandler != null) { + if (other.retryHandler != null) return false; - } - } else if (!retryHandler.compare(other.retryHandler)) { - return false; } + else if (!retryHandler.compare(other.retryHandler)) + return false; if (timeouts == null) { - if (other.timeouts != null) { + if (other.timeouts != null) return false; - } - } else if (!timeouts.equals(other.timeouts)) { - return false; } + else if (!timeouts.equals(other.timeouts)) + return false; return true; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java index 24e2f909bc..982453246f 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,33 +25,36 @@ import org.apache.http.client.UserTokenHandler; import org.apache.http.client.config.RequestConfig; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.http.config.ClientCertificate; +import org.openecomp.sdc.common.log.interceptors.ApacheClientLogRequestInterceptor; +import org.openecomp.sdc.common.log.interceptors.ApacheClientLogResponseInterceptor; import org.openecomp.sdc.common.log.wrappers.Logger; public class HttpClientFactory { - private static final Logger LOGGER = Logger.getLogger(HttpClientFactory.class.getName()); - private static final UserTokenHandler USER_TOKEN_HANDLER = context -> null; + private static final Logger logger = Logger.getLogger(HttpClientFactory.class.getName()); + private static final UserTokenHandler userTokenHandler = context -> null; private final HttpConnectionMngFactory connectionMngFactory; - + HttpClientFactory(HttpConnectionMngFactory connectionMngFactory) { this.connectionMngFactory = connectionMngFactory; } HttpClient createClient(String protocol, HttpClientConfigImmutable config) { - LOGGER.debug("Create {} client based on {}", protocol, config); + logger.debug("Create {} client based on {}", protocol, config); - ClientCertificate clientCertificate = Constants.HTTPS.equals(protocol) ? config.getClientCertificate() : null; + ClientCertificate clientCertificate = Constants.HTTPS.equals(protocol) ? config.getClientCertificate() : null; HttpClientConnectionManager connectionManager = connectionMngFactory.getOrCreate(clientCertificate); RequestConfig requestConfig = createClientTimeoutConfiguration(config); CloseableHttpClient client = HttpClients.custom() - .setDefaultRequestConfig(requestConfig) - .setConnectionManager(connectionManager) - .setUserTokenHandler(USER_TOKEN_HANDLER) - .setRetryHandler(resolveRetryHandler(config)) - .build(); + .setDefaultRequestConfig(requestConfig) + .setConnectionManager(connectionManager) + .setUserTokenHandler(userTokenHandler) + .setRetryHandler(resolveRetryHandler(config)) + .build(); return new HttpClient(client, config); } @@ -59,7 +62,7 @@ public class HttpClientFactory { private HttpRequestRetryHandler resolveRetryHandler(HttpClientConfigImmutable config) { return config.getNumOfRetries() > 0 ? config.getRetryHandler() : null; } - + private RequestConfig createClientTimeoutConfiguration(HttpClientConfigImmutable config) { return RequestConfig.custom() .setConnectTimeout(config.getConnectTimeoutMs()) diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java index d5d03329bb..c5634eaf8c 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -48,42 +48,43 @@ public class HttpConnectionMngFactory { private static final String P12_KEYSTORE_EXTENTION = ".p12"; private static final String PFX_KEYSTORE_EXTENTION = ".pfx"; private static final String JKS_KEYSTORE_EXTENTION = ".jks"; - + private static final String P12_KEYSTORE_TYPE = "pkcs12"; private static final String JKS_KEYSTORE_TYPE = "jks"; - - private static final Logger LOGGER = Logger.getLogger(HttpConnectionMngFactory.class.getName()); + + private static final Logger logger = Logger.getLogger(HttpConnectionMngFactory.class.getName()); private static final int DEFAULT_CONNECTION_POOL_SIZE = 30; private static final int DEFAULT_MAX_CONNECTION_PER_ROUTE = 5; private static final int VALIDATE_CONNECTION_AFTER_INACTIVITY_MS = 10000; - + private Map sslClientConnectionManagers = new ConcurrentHashMap<>(); private HttpClientConnectionManager plainClientConnectionManager; - + HttpConnectionMngFactory() { plainClientConnectionManager = createConnectionMng(null); } HttpClientConnectionManager getOrCreate(ClientCertificate clientCertificate) { - if (clientCertificate == null) { + if(clientCertificate == null) { return plainClientConnectionManager; } return sslClientConnectionManagers.computeIfAbsent(clientCertificate, k -> createConnectionMng(clientCertificate)); } - + private HttpClientConnectionManager createConnectionMng(ClientCertificate clientCertificate) { SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); SSLConnectionSocketFactory sslsf = null; try { sslContextBuilder.loadTrustMaterial(new TrustSelfSignedStrategy()); - - if (clientCertificate != null) { + + if(clientCertificate != null) { setClientSsl(clientCertificate, sslContextBuilder); } sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE); - } catch (GeneralSecurityException e) { - LOGGER.debug("Create SSL connection socket factory failed with exception, use default SSL factory ", e); + } + catch (GeneralSecurityException e) { + logger.debug("Create SSL connection socket factory failed with exception, use default SSL factory ", e); sslsf = SSLConnectionSocketFactory.getSocketFactory(); } @@ -105,12 +106,13 @@ public class HttpConnectionMngFactory { char[] keyStorePassword = clientCertificate.getKeyStorePassword().toCharArray(); KeyStore clientKeyStore = createClientKeyStore(clientCertificate.getKeyStore(), keyStorePassword); sslContextBuilder.loadKeyMaterial(clientKeyStore, keyStorePassword); - LOGGER.debug("#setClientSsl - Set Client Certificate authentication"); - } catch (IOException | GeneralSecurityException e) { - LOGGER.debug("#setClientSsl - Set Client Certificate authentication failed with exception, diasable client SSL authentication ", e); + logger.debug("#setClientSsl - Set Client Certificate authentication"); + } + catch (IOException | GeneralSecurityException e) { + logger.debug("#setClientSsl - Set Client Certificate authentication failed with exception, diasable client SSL authentication ", e); } } - + private KeyStore createClientKeyStore(String keyStorePath, char[] keyStorePassword) throws IOException, GeneralSecurityException { KeyStore keyStore = null; try (InputStream stream = new FileInputStream(keyStorePath)) { @@ -119,14 +121,15 @@ public class HttpConnectionMngFactory { } return keyStore; } - + private String getKeyStoreType(String keyStore) { - if (!StringUtils.isEmpty(keyStore)) { - if (keyStore.endsWith(P12_KEYSTORE_EXTENTION) || keyStore.endsWith(PFX_KEYSTORE_EXTENTION)) { + if(!StringUtils.isEmpty(keyStore)) { + if(keyStore.endsWith(P12_KEYSTORE_EXTENTION) || keyStore.endsWith(PFX_KEYSTORE_EXTENTION)) { return P12_KEYSTORE_TYPE; - } else if (keyStore.endsWith(JKS_KEYSTORE_EXTENTION)) { - return JKS_KEYSTORE_TYPE; } + else if(keyStore.endsWith(JKS_KEYSTORE_EXTENTION)) { + return JKS_KEYSTORE_TYPE; + } } return KeyStore.getDefaultType(); } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java index 2b2e7a4f12..8487e1ff72 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,17 +25,17 @@ public class HttpExecuteException extends Exception { private static final long serialVersionUID = 1L; public HttpExecuteException(String message) { - super(message); + super (message); } public HttpExecuteException(String message, Throwable cause) { - super(message, cause); + super (message, cause); } public HttpExecuteException(Throwable cause) { super(cause); } - + @Override public Throwable getCause() { Throwable cause = super.getCause(); diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java index b418ce744e..57e5cb2bed 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,34 +28,27 @@ import java.util.Properties; //TODO- remove all static and use instance methods for better testing public abstract class HttpRequest { - private static final Properties DEFAULT_HEADERS = null; - private static final HttpClientConfig DEFAULT_CONFIG = new HttpClientConfig(); + static final Properties defaultHeaders = null; + static final HttpClientConfig defaultConfig = new HttpClientConfig(); - private HttpRequest() { - } - - public static Properties getDefaultHeaders() { - return DEFAULT_HEADERS; - } - public static HttpClientConfig getDefaultConfig() { - return DEFAULT_CONFIG; + private HttpRequest() { } /* * GET response as string */ public static HttpResponse get(String url) throws HttpExecuteException { - return get(url, DEFAULT_HEADERS, DEFAULT_CONFIG); + return get(url, defaultHeaders, defaultConfig); } public static HttpResponse get(String url, Properties headers) throws HttpExecuteException { - return get(url, headers, DEFAULT_CONFIG); + return get(url, headers, defaultConfig); } - + public static HttpResponse get(String url, HttpClientConfig config) throws HttpExecuteException { - return get(url, DEFAULT_HEADERS, config); + return get(url, defaultHeaders, config); } public static HttpResponse get(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { @@ -66,15 +59,15 @@ public abstract class HttpRequest { * GET response as byte array */ public static HttpResponse getAsByteArray(String url) throws HttpExecuteException { - return getAsByteArray(url, DEFAULT_HEADERS, DEFAULT_CONFIG); + return getAsByteArray(url, defaultHeaders, defaultConfig); } public static HttpResponse getAsByteArray(String url, Properties headers) throws HttpExecuteException { - return getAsByteArray(url, headers, DEFAULT_CONFIG); + return getAsByteArray(url, headers, defaultConfig); } public static HttpResponse getAsByteArray(String url, HttpClientConfig config) throws HttpExecuteException { - return getAsByteArray(url, DEFAULT_HEADERS, config); + return getAsByteArray(url, defaultHeaders, config); } public static HttpResponse getAsByteArray(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { @@ -85,15 +78,15 @@ public abstract class HttpRequest { * PUT */ public static HttpResponse put(String url, HttpEntity entity) throws HttpExecuteException { - return put(url, DEFAULT_HEADERS, entity, DEFAULT_CONFIG); + return put(url, defaultHeaders, entity, defaultConfig); } public static HttpResponse put(String url, Properties headers, HttpEntity entity) throws HttpExecuteException { - return put(url, headers, entity, DEFAULT_CONFIG); + return put(url, headers, entity, defaultConfig); } - + public static HttpResponse put(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { - return put(url, DEFAULT_HEADERS, entity, config); + return put(url, defaultHeaders, entity, config); } public static HttpResponse put(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { @@ -104,59 +97,59 @@ public abstract class HttpRequest { * POST */ public static HttpResponse post(String url, HttpEntity entity) throws HttpExecuteException { - return post(url, DEFAULT_HEADERS, entity, DEFAULT_CONFIG); + return post(url, defaultHeaders, entity, defaultConfig); } public static HttpResponse post(String url, Properties headers, HttpEntity entity) throws HttpExecuteException { - return post(url, headers, entity, DEFAULT_CONFIG); + return post(url, headers, entity, defaultConfig); } - + public static HttpResponse post(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { - return post(url, DEFAULT_HEADERS, entity, config); + return post(url, defaultHeaders, entity, config); } public static HttpResponse post(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { return HttpRequestHandler.get().post(url, headers, entity, config); } - + /* * PATCH */ public static HttpResponse patch(String url, HttpEntity entity) throws HttpExecuteException { - return patch(url, DEFAULT_HEADERS, entity, DEFAULT_CONFIG); + return patch(url, defaultHeaders, entity, defaultConfig); } public static HttpResponse patch(String url, Properties headers, HttpEntity entity) throws HttpExecuteException { - return patch(url, headers, entity, DEFAULT_CONFIG); + return patch(url, headers, entity, defaultConfig); } - + public static HttpResponse patch(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { - return patch(url, DEFAULT_HEADERS, entity, config); + return patch(url, defaultHeaders, entity, config); } public static HttpResponse patch(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { return HttpRequestHandler.get().patch(url, headers, entity, config); } - + /* * DELETE */ public static HttpResponse delete(String url) throws HttpExecuteException { - return delete(url, DEFAULT_HEADERS, DEFAULT_CONFIG); + return delete(url, defaultHeaders, defaultConfig); } public static HttpResponse delete(String url, Properties headers) throws HttpExecuteException { - return delete(url, headers, DEFAULT_CONFIG); + return delete(url, headers, defaultConfig); } - + public static HttpResponse delete(String url, HttpClientConfig config) throws HttpExecuteException { - return delete(url, DEFAULT_HEADERS, config); + return delete(url, defaultHeaders, config); } public static HttpResponse delete(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { return HttpRequestHandler.get().delete(url, headers, config); } - + public static void destroy() { HttpRequestHandler.get().destroy(); } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java index e4747f4308..73f0f15354 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -38,10 +38,10 @@ public class HttpRequestHandler { private static HttpRequestHandler handlerInstance = new HttpRequestHandler(); private static final String HTTPS_PREFIX = "https://"; private static final String HTTP_PREFIX = "http://"; - + private Map clients = new ConcurrentHashMap<>(); private HttpClientFactory clientFactory; - + private FunctionThrows, Exception> byteResponseBuilder = (CloseableHttpResponse httpResponse) -> { HttpEntity entity = httpResponse.getEntity(); byte[] response = null; @@ -51,8 +51,8 @@ public class HttpRequestHandler { response = IOUtils.toByteArray(content); } } - return new HttpResponse<>(response, - httpResponse.getStatusLine().getStatusCode(), + return new HttpResponse<>(response, + httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase()); }; @@ -62,7 +62,7 @@ public class HttpRequestHandler { if (entity != null) { response = EntityUtils.toString(entity); } - return new HttpResponse<>(response, + return new HttpResponse<>(response, httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase()); }; @@ -71,7 +71,7 @@ public class HttpRequestHandler { HttpConnectionMngFactory connectionMngFactory = new HttpConnectionMngFactory(); clientFactory = new HttpClientFactory(connectionMngFactory); } - + public static HttpRequestHandler get() { return handlerInstance; } @@ -81,7 +81,7 @@ public class HttpRequestHandler { return client.get(url, headers, stringResponseBuilder); } - public HttpResponse getAsByteArray(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { + public HttpResponse getAsByteArray(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { HttpClient client = getOrCreateClient(url, config); return client.get(url, headers, byteResponseBuilder); } @@ -102,15 +102,15 @@ public class HttpRequestHandler { } public HttpResponse delete(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { - HttpClient client = getOrCreateClient(url, config != null ? config : HttpRequest.getDefaultConfig()); + HttpClient client = getOrCreateClient(url, config != null ? config : HttpRequest.defaultConfig); return client.delete(url, headers, stringResponseBuilder); } - + public void destroy() { clients.forEach((k, v) -> v.close()); clients.clear(); } - + private HttpClient getOrCreateClient(String url, HttpClientConfig config) throws HttpExecuteException { String protocol = getProtocol(url); HttpClientConfigImmutable httpClientConfigImmutable = HttpClientConfigImmutable.getOrCreate(config); @@ -129,10 +129,12 @@ public class HttpRequestHandler { private String getProtocol(String url) throws HttpExecuteException { if (url.startsWith(HTTPS_PREFIX)) { return Constants.HTTPS; - } else if (url.startsWith(HTTP_PREFIX)) { + } + else if (url.startsWith(HTTP_PREFIX)) { return Constants.HTTP; - } else { - throw new HttpExecuteException(String.format("Failed to create http client. Requested protocol is not supported \"%s\"", url)); } + else { + throw new HttpExecuteException(String.format("Failed to create http client. Requested protocol is not supported \"%s\"", url)); + } } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java index b3a4a96b2f..c6061cf1c2 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ public class HttpResponse { this.statusCode = statusCode; this.description = StringUtils.EMPTY; } - + public HttpResponse(T response, int statusCode, String description) { this.response = response; this.statusCode = statusCode; @@ -63,6 +63,6 @@ public class HttpResponse { builder.append("]"); return builder.toString(); } - - + + } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java index 88c4a4fe87..71f9ac2629 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,7 +24,7 @@ import org.apache.http.HttpStatus; public final class Responses { public static final HttpResponse INTERNAL_SERVER_ERROR = new HttpResponse<>("Internal server error", HttpStatus.SC_INTERNAL_SERVER_ERROR); - + private Responses() { } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java index efac5c18ef..7b39e3f8c9 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java index f611ad6eba..bbcd815e75 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,15 +27,14 @@ import java.io.IOException; public class RetryHandlers { - private static final Logger LOGGER = Logger.getLogger(RetryHandlers.class.getName()); + private static final Logger logger = Logger.getLogger(RetryHandlers.class.getName()); - private RetryHandlers() { - } + private RetryHandlers(){} public static ComparableHttpRequestRetryHandler getDefault(int numOfRetries) { return (IOException exception, int executionCount, HttpContext context) -> { - LOGGER.debug("failed sending request with exception", exception); - LOGGER.debug("try request number: {}", executionCount); + logger.debug("failed sending request with exception", exception); + logger.debug("try request number: {}", executionCount); return executionCount <= numOfRetries; }; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/BasicAuthorization.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/BasicAuthorization.java index 47338b77e7..124c7ea0c8 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/BasicAuthorization.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/BasicAuthorization.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,7 +22,7 @@ package org.openecomp.sdc.common.http.config; import fj.data.Either; import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.security.SecurityUtil; +import org.onap.sdc.security.SecurityUtil; public class BasicAuthorization { private String userName; @@ -53,17 +53,19 @@ public class BasicAuthorization { return password; } - + private void setPassword(String password, boolean isEncoded) { validate(password); - if (isEncoded) { + if(isEncoded) { Either passkey = SecurityUtil.INSTANCE.decrypt(password); - if (passkey.isLeft()) { + if(passkey.isLeft()) { this.password = passkey.left().value(); - } else { + } + else { throw new IllegalArgumentException(passkey.right().value()); } - } else { + } + else { this.password = password; } } @@ -79,28 +81,26 @@ public class BasicAuthorization { @Override public boolean equals(Object obj) { - if (this == obj) { + if (this == obj) return true; - } - if (obj == null) { + if (obj == null) return false; - } - if (getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) return false; - } BasicAuthorization other = (BasicAuthorization) obj; if (password == null) { - if (other.password != null) { + if (other.password != null) return false; - } - } else if (!password.equals(other.password)) { - return false; } + else if (!password.equals(other.password)) + return false; if (userName == null) { - return other.userName == null; - } else { - return userName.equals(other.userName); + if (other.userName != null) + return false; } + else if (!userName.equals(other.userName)) + return false; + return true; } @Override @@ -113,7 +113,7 @@ public class BasicAuthorization { } private void validate(String str) { - if (StringUtils.isEmpty(str)) { + if(StringUtils.isEmpty(str)) { throw new IllegalArgumentException("BasicAuthorization username and/or password cannot be empty"); } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ClientCertificate.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ClientCertificate.java index 259d965b0d..1f6c070094 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ClientCertificate.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ClientCertificate.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,7 +22,7 @@ package org.openecomp.sdc.common.http.config; import fj.data.Either; import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.security.SecurityUtil; +import org.onap.sdc.security.SecurityUtil; public class ClientCertificate { private String keyStore; @@ -35,7 +35,7 @@ public class ClientCertificate { setKeyStore(clientCertificate.getKeyStore()); setKeyStorePassword(clientCertificate.getKeyStorePassword(), false); } - + public void setKeyStore(String keyStore) { validate(keyStore); this.keyStore = keyStore; @@ -47,14 +47,16 @@ public class ClientCertificate { private void setKeyStorePassword(String keyStorePassword, boolean isEncoded) { validate(keyStorePassword); - if (isEncoded) { + if(isEncoded) { Either passkey = SecurityUtil.INSTANCE.decrypt(keyStorePassword); if (passkey.isLeft()) { this.keyStorePassword = passkey.left().value(); - } else { + } + else { throw new IllegalArgumentException(passkey.right().value()); } - } else { + } + else { this.keyStorePassword = keyStorePassword; } } @@ -66,7 +68,7 @@ public class ClientCertificate { public String getKeyStorePassword() { return keyStorePassword; } - + @Override public int hashCode() { final int prime = 31; @@ -78,37 +80,39 @@ public class ClientCertificate { @Override public boolean equals(Object obj) { - if (this == obj) { + if (this == obj) return true; - } - if (obj == null) { + if (obj == null) return false; - } - if (getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) return false; - } ClientCertificate other = (ClientCertificate) obj; if (keyStore == null) { - if (other.keyStore != null) { + if (other.keyStore != null) return false; - } - } else if (!keyStore.equals(other.keyStore)) { - return false; } + else if (!keyStore.equals(other.keyStore)) + return false; if (keyStorePassword == null) { - return other.keyStorePassword == null; - } else { - return keyStorePassword.equals(other.keyStorePassword); + if (other.keyStorePassword != null) + return false; } + else if (!keyStorePassword.equals(other.keyStorePassword)) + return false; + return true; } @Override public String toString() { - return "ClientCertificate [keyStore=" + keyStore + "]"; + StringBuilder builder = new StringBuilder(); + builder.append("ClientCertificate [keyStore="); + builder.append(keyStore); + builder.append("]"); + return builder.toString(); } - + private void validate(String str) { - if (StringUtils.isEmpty(str)) { + if(StringUtils.isEmpty(str)) { throw new IllegalArgumentException("ClientCertificate keystore and/or kestorePassword cannot be empty"); } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ExternalServiceConfig.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ExternalServiceConfig.java index 2af8e74447..dcc9b73bcd 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ExternalServiceConfig.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ExternalServiceConfig.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,14 +21,14 @@ package org.openecomp.sdc.common.http.config; public class ExternalServiceConfig { - + private HttpRequestConfig httpRequestConfig; private HttpClientConfig httpClientConfig; public HttpRequestConfig getHttpRequestConfig() { return httpRequestConfig; } - + public void setHttpRequestConfig(HttpRequestConfig httpRequestConfig) { this.httpRequestConfig = httpRequestConfig; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpClientConfig.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpClientConfig.java index 3ed3b7c86c..a4f12e3eec 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpClientConfig.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpClientConfig.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,6 +20,8 @@ package org.openecomp.sdc.common.http.config; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.nustaq.serialization.annotations.Serialize; import org.openecomp.sdc.common.http.client.api.ComparableHttpRequestRetryHandler; import java.util.Map; @@ -32,10 +34,12 @@ public class HttpClientConfig { private Timeouts timeouts = Timeouts.DEFAULT; private Map headers; private int numOfRetries; + @JsonIgnore + private boolean enableMetricLogging = false; - public HttpClientConfig() { + public HttpClientConfig() { } - + public HttpClientConfig(Timeouts timeouts) { setTimeouts(timeouts); } @@ -81,11 +85,11 @@ public class HttpClientConfig { public void setClientCertificate(ClientCertificate clientCertificate) { this.clientCertificate = clientCertificate; } - + public Map getHeaders() { return headers; } - + public void setHeaders(Map headers) { this.headers = headers; } @@ -93,11 +97,19 @@ public class HttpClientConfig { public int getNumOfRetries() { return numOfRetries; } - + public void setNumOfRetries(int numOfRetries) { this.numOfRetries = numOfRetries; } + public boolean isEnableMetricLogging() { + return enableMetricLogging; + } + + public void setEnableMetricLogging(boolean enableMetricLogging) { + this.enableMetricLogging = enableMetricLogging; + } + @Override public String toString() { StringBuilder builder = new StringBuilder(); @@ -113,6 +125,8 @@ public class HttpClientConfig { builder.append(headers); builder.append(", numOfRetries="); builder.append(numOfRetries); + builder.append(", enableMetricLogging="); + builder.append(enableMetricLogging); builder.append("]"); return builder.toString(); } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpRequestConfig.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpRequestConfig.java index 89e3532a10..040d068dfe 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpRequestConfig.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpRequestConfig.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,22 +27,22 @@ public class HttpRequestConfig { private String serverRootUrl; private Map resourceNamespaces; - + public String getServerRootUrl() { return serverRootUrl; } - + public void setServerRootUrl(String serverRootUrl) { this.serverRootUrl = serverRootUrl; } - + public Map getResourceNamespaces() { - if (resourceNamespaces == null) { + if(resourceNamespaces == null) { resourceNamespaces = new HashMap<>(); } return resourceNamespaces; } - + public void setResourceNamespaces(Map resourceNamespaces) { this.resourceNamespaces = resourceNamespaces; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/Timeouts.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/Timeouts.java index e8711f4d12..39ef8555ad 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/Timeouts.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/Timeouts.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,9 +28,8 @@ public class Timeouts { private int connectPoolTimeoutMs = DEFAULT_TIMEOUT_MS; public static final Timeouts DEFAULT; - static { - DEFAULT = new Timeouts(); + DEFAULT = new Timeouts(); } private Timeouts() { @@ -50,30 +49,30 @@ public class Timeouts { public int getConnectTimeoutMs() { return connectTimeoutMs; } - + public void setConnectTimeoutMs(int connectTimeoutMs) { validate(connectTimeoutMs); this.connectTimeoutMs = connectTimeoutMs; } - + public int getReadTimeoutMs() { return readTimeoutMs; } - + public void setReadTimeoutMs(int readTimeoutMs) { validate(readTimeoutMs); this.readTimeoutMs = readTimeoutMs; } - + public int getConnectPoolTimeoutMs() { return connectPoolTimeoutMs; } - + public void setConnectPoolTimeoutMs(int connectPoolTimeoutMs) { validate(connectPoolTimeoutMs); this.connectPoolTimeoutMs = connectPoolTimeoutMs; } - + @Override public int hashCode() { final int prime = 31; @@ -83,38 +82,40 @@ public class Timeouts { result = prime * result + readTimeoutMs; return result; } - + @Override public boolean equals(Object obj) { - if (this == obj) { + if (this == obj) return true; - } - if (obj == null) { + if (obj == null) return false; - } - if (getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) return false; - } Timeouts other = (Timeouts) obj; - if (connectPoolTimeoutMs != other.connectPoolTimeoutMs) { + if (connectPoolTimeoutMs != other.connectPoolTimeoutMs) return false; - } - if (connectTimeoutMs != other.connectTimeoutMs) { + if (connectTimeoutMs != other.connectTimeoutMs) return false; - } - return readTimeoutMs == other.readTimeoutMs; + if (readTimeoutMs != other.readTimeoutMs) + return false; + return true; } - + @Override public String toString() { - return "Timeouts [connectTimeoutMs=" + connectTimeoutMs - + ", readTimeoutMs=" + readTimeoutMs - + ", connectPoolTimeoutMs=" + connectPoolTimeoutMs - + "]"; + StringBuilder builder = new StringBuilder(); + builder.append("Timeouts [connectTimeoutMs="); + builder.append(connectTimeoutMs); + builder.append(", readTimeoutMs="); + builder.append(readTimeoutMs); + builder.append(", connectPoolTimeoutMs="); + builder.append(connectPoolTimeoutMs); + builder.append("]"); + return builder.toString(); } - + private void validate(int timeout) { - if (timeout <= 0) { + if(timeout <= 0) { throw new IllegalArgumentException("Timeout values cannot be less than zero"); } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ConfigFileChangeListener.java b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ConfigFileChangeListener.java index f1f1305ee9..e243bac730 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ConfigFileChangeListener.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ConfigFileChangeListener.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -35,111 +35,111 @@ import java.util.Map; public class ConfigFileChangeListener extends FileChangeListener { - private static Logger log = Logger.getLogger(ConfigFileChangeListener.class.getName()); + private static Logger log = Logger.getLogger(ConfigFileChangeListener.class.getName()); - private Map> fileChangeToCallBack = new HashMap<>(); + private Map> fileChangeToCallBack = new HashMap<>(); - private Object lock = new Object(); + private Object lock = new Object(); - private YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); + private YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); - @Override - public void onFileChange(File pFile) { + @Override + public void onFileChange(File pFile) { - super.onFileChange(pFile); + super.onFileChange(pFile); - if (pFile != null) { + if (pFile != null) { - if (fileChangeToCallBack != null) { + if (fileChangeToCallBack != null) { - String id = findIdFromFileName(pFile.getName()); + String id = findIdFromFileName(pFile.getName()); - if (id != null) { + if (id != null) { - List listeners = fileChangeToCallBack.get(id); - if (listeners != null) { - for (ConfigurationListener configurationListener : listeners) { + List listeners = fileChangeToCallBack.get(id); + if (listeners != null) { + for (ConfigurationListener configurationListener : listeners) { - Class configClass = configurationListener.getType(); + Class configClass = configurationListener.getType(); - BasicConfiguration basicConfiguration = yamlToObjectConverter.convert(pFile.getAbsolutePath(), configClass); + BasicConfiguration basicConfiguration = yamlToObjectConverter.convert(pFile.getAbsolutePath(), configClass); - if (basicConfiguration == null) { - log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Cannot update the listeners for file Change since the file content is invalid"); - continue; - } - log.debug("Loaded configuration after converting is {}", basicConfiguration); + if (basicConfiguration == null) { + log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Cannot update the listeners for file Change since the file content is invalid"); + continue; + } + log.debug("Loaded configuration after converting is {}", basicConfiguration); - configurationListener.getCallBack().reconfigure(basicConfiguration); + configurationListener.getCallBack().reconfigure(basicConfiguration); - } - } - } else { + } + } + } else { - log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Cannot calculate id from file {}", pFile.getName()); - } - } + log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Cannot calculate id from file {}", pFile.getName()); + } + } - } + } - log.debug("File {} was changed.", pFile); - } + log.debug("File {} was changed.", pFile); + } - private String findIdFromFileName(String name) { + private String findIdFromFileName(String name) { - String result = null; - if (name != null) { - int startIndex = 0; - int endIndex = name.length(); - if (name.contains(File.separator)) { - startIndex = name.lastIndexOf(File.separator); - } - // String subNameString = name.substring(startIndex, endIndex); - // if (subNameString.contains(".")) { - // endIndex = subNameString.indexOf("."); - // } + String result = null; + if (name != null) { + int startIndex = 0; + int endIndex = name.length(); + if (name.contains(File.separator)) { + startIndex = name.lastIndexOf(File.separator); + } + // String subNameString = name.substring(startIndex, endIndex); + // if (subNameString.contains(".")) { + // endIndex = subNameString.indexOf("."); + // } - result = name.substring(startIndex, endIndex); + result = name.substring(startIndex, endIndex); - } + } - return result; - } + return result; + } - public void register(String id, ConfigurationListener configurationListener) { + public void register(String id, ConfigurationListener configurationListener) { - if (configurationListener != null) { + if (configurationListener != null) { - synchronized (lock) { + synchronized (lock) { - List callbacks = fileChangeToCallBack.get(id); - if (callbacks == null) { - callbacks = new ArrayList<>(); - fileChangeToCallBack.put(id, callbacks); - } - callbacks.add(configurationListener); + List callbacks = fileChangeToCallBack.get(id); + if (callbacks == null) { + callbacks = new ArrayList<>(); + fileChangeToCallBack.put(id, callbacks); + } + callbacks.add(configurationListener); - } + } - } + } - } + } - // public void notify(String id, BasicConfiguration object) { - // - // if (fileChangeToCallBack != null) { - // List listeners = fileChangeToCallBack - // .get(id); - // if (listeners != null) { - // for (ConfigurationListener configurationListener : listeners) { - // - // configurationListener.getCallBack().reconfigure(object); - // - // } - // } - // } - // - // } + // public void notify(String id, BasicConfiguration object) { + // + // if (fileChangeToCallBack != null) { + // List listeners = fileChangeToCallBack + // .get(id); + // if (listeners != null) { + // for (ConfigurationListener configurationListener : listeners) { + // + // configurationListener.getCallBack().reconfigure(object); + // + // } + // } + // } + // + // } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ExternalConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ExternalConfiguration.java index f1a1f490ca..79a78828e8 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ExternalConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ExternalConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,80 +26,81 @@ import org.openecomp.sdc.common.api.ConfigurationSource; import java.io.File; /** + * * Save the - * + * * @author esofer + * */ public class ExternalConfiguration { - public static final int FILESYSTEM_MONITOR_INTERVAL = 1000; - private static String appName; - private static String appVersion; - private static String configDir; - private static ConfigurationSource configurationSource; - - private static FilesystemAlterationMonitor fam = null; - - private static ConfigFileChangeListener changeListener = new ConfigFileChangeListener(); - - private static boolean enableReconfigure = true; - - public static String getAppName() { - return appName; - } - - public static void setAppName(String appName) { - ExternalConfiguration.appName = appName; - } - - public static String getAppVersion() { - return appVersion; - } - - public static void setAppVersion(String appVersion) { - ExternalConfiguration.appVersion = appVersion; - } - - public static String getConfigDir() { - return configDir; - } - - public static void setConfigDir(String configDir) { - ExternalConfiguration.configDir = configDir; - } - - public static ConfigurationSource getConfigurationSource() { - return configurationSource; - } - - public static void setConfigurationSource(ConfigurationSource configurationSource) { - ExternalConfiguration.configurationSource = configurationSource; - } - - public static ConfigFileChangeListener getChangeListener() { - return changeListener; - } - - public static void listenForChanges() { - - String watchingDir = configDir + File.separator + appName; - if (enableReconfigure) { - if (fam == null) { - fam = new FilesystemAlterationMonitor(); - fam.setInterval(FILESYSTEM_MONITOR_INTERVAL); - fam.addListener(new File(watchingDir), changeListener); - fam.start(); - } - } - } - - public static void stopListenForFileChanges() { - if (enableReconfigure) { - if (fam != null) { - fam.stop(); - fam = null; - } - } - } + private static String appName; + private static String appVersion; + private static String configDir; + private static ConfigurationSource configurationSource; + + private static FilesystemAlterationMonitor fam = null; + + private static ConfigFileChangeListener changeListener = new ConfigFileChangeListener(); + + private static boolean enableReconfigure = true; + + public static String getAppName() { + return appName; + } + + public static void setAppName(String appName) { + ExternalConfiguration.appName = appName; + } + + public static String getAppVersion() { + return appVersion; + } + + public static void setAppVersion(String appVersion) { + ExternalConfiguration.appVersion = appVersion; + } + + public static String getConfigDir() { + return configDir; + } + + public static void setConfigDir(String configDir) { + ExternalConfiguration.configDir = configDir; + } + + public static ConfigurationSource getConfigurationSource() { + return configurationSource; + } + + public static void setConfigurationSource(ConfigurationSource configurationSource) { + ExternalConfiguration.configurationSource = configurationSource; + } + + public static ConfigFileChangeListener getChangeListener() { + return changeListener; + } + + public static void listenForChanges() { + + String watchingDir = configDir + File.separator + appName; + if (enableReconfigure) { + if (fam == null) { + fam = new FilesystemAlterationMonitor(); + fam.setInterval(1000); + fam.addListener(new File(watchingDir), changeListener); + fam.start(); + } + } + } + + public static void stopListenForFileChanges() { + if (enableReconfigure) { + if (fam != null) { + fam.stop(); + fam = null; + } + } + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/FSConfigurationSource.java b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/FSConfigurationSource.java index 3aa220c5bc..8cab431594 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/FSConfigurationSource.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/FSConfigurationSource.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,8 +31,9 @@ import org.openecomp.sdc.common.util.YamlToObjectConverter; /** * Read configuration from file system - * + * * @author esofer + * */ public class FSConfigurationSource implements ConfigurationSource { @@ -41,50 +42,50 @@ public class FSConfigurationSource implements ConfigurationSource { private final ConfigFileChangeListener changeListener; private final String appConfigDir; - public FSConfigurationSource(ConfigFileChangeListener changeListener, String appConfigDir) { - super(); - this.changeListener = changeListener; - this.appConfigDir = appConfigDir; - } + public FSConfigurationSource(ConfigFileChangeListener changeListener, String appConfigDir) { + super(); + this.changeListener = changeListener; + this.appConfigDir = appConfigDir; + } - /* - * get and watch configuration changes. The file name we looking for is the lower case of the class name separated by "-". - * - * (non-Javadoc) - * - * @see org.openecomp.sdc.common.api.ConfigurationSource#getAndWatchConfiguration (java.lang.Class, org.openecomp.sdc.common.api.ConfigurationListener) - */ - public T getAndWatchConfiguration(Class className, ConfigurationListener configurationListener) { + /* + * get and watch configuration changes. The file name we looking for is the lower case of the class name separated by "-". + * + * (non-Javadoc) + * + * @see org.openecomp.sdc.common.api.ConfigurationSource#getAndWatchConfiguration (java.lang.Class, org.openecomp.sdc.common.api.ConfigurationListener) + */ + public T getAndWatchConfiguration(Class className, ConfigurationListener configurationListener) { - String configFileName = calculateFileName(className); + String configFileName = calculateFileName(className); - T object = yamlToObjectConverter.convert(this.appConfigDir, className, configFileName); + T object = yamlToObjectConverter.convert(this.appConfigDir, className, configFileName); - if (configurationListener != null && changeListener != null) { - if (object != null) { - changeListener.register(configFileName, configurationListener); - } - } + if (configurationListener != null && changeListener != null) { + if (object != null) { + changeListener.register(configFileName, configurationListener); + } + } - return object; - } + return object; + } - public void addWatchConfiguration(Class className, ConfigurationListener configurationListener) { + public void addWatchConfiguration(Class className, ConfigurationListener configurationListener) { - String configFileName = calculateFileName(className); + String configFileName = calculateFileName(className); - if (configurationListener != null) { - changeListener.register(configFileName, configurationListener); - } + if (configurationListener != null) { + changeListener.register(configFileName, configurationListener); + } - } + } - /** - * convert camel case string to list of words separated by "-" where each word is in lower case format. For example, MyClass will be calculated to be my-class.yaml . - * - * @param className - * @return file name based on the class name - */ + /** + * convert camel case string to list of words separated by "-" where each word is in lower case format. For example, MyClass will be calculated to be my-class.yaml . + * + * @param className + * @return file name based on the class name + */ static String calculateFileName(Class className) { String[] words = className.getSimpleName().split("(?=\\p{Upper})"); diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/MutableHttpServletRequest.java b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/MutableHttpServletRequest.java index 90ab998557..3b88ff8978 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/MutableHttpServletRequest.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/MutableHttpServletRequest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,51 +22,46 @@ package org.openecomp.sdc.common.impl; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; +import java.util.*; public final class MutableHttpServletRequest extends HttpServletRequestWrapper { - // holds custom header and value mapping - private final Map customHeaders; + // holds custom header and value mapping + private final Map customHeaders; - public MutableHttpServletRequest(HttpServletRequest request) { - super(request); - this.customHeaders = new HashMap<>(); - } + public MutableHttpServletRequest(HttpServletRequest request) { + super(request); + this.customHeaders = new HashMap<>(); + } - public void putHeader(String name, String value) { - this.customHeaders.put(name, value); - } + public void putHeader(String name, String value) { + this.customHeaders.put(name, value); + } - public String getHeader(String name) { - // check the custom headers first - String headerValue = customHeaders.get(name); + public String getHeader(String name) { + // check the custom headers first + String headerValue = customHeaders.get(name); - if (headerValue != null) { - return headerValue; - } - // else return from into the original wrapped object - return ((HttpServletRequest) getRequest()).getHeader(name); - } + if (headerValue != null) { + return headerValue; + } + // else return from into the original wrapped object + return ((HttpServletRequest) getRequest()).getHeader(name); + } - public Enumeration getHeaderNames() { - // create a set of the custom header names - Set set = new HashSet<>(customHeaders.keySet()); + public Enumeration getHeaderNames() { + // create a set of the custom header names + Set set = new HashSet<>(customHeaders.keySet()); - // now add the headers from the wrapped request object - @SuppressWarnings("unchecked") - Enumeration e = ((HttpServletRequest) getRequest()).getHeaderNames(); - while (e.hasMoreElements()) { - // add the names of the request headers into the list - String n = e.nextElement(); - set.add(n); - } + // now add the headers from the wrapped request object + @SuppressWarnings("unchecked") + Enumeration e = ((HttpServletRequest) getRequest()).getHeaderNames(); + while (e.hasMoreElements()) { + // add the names of the request headers into the list + String n = e.nextElement(); + set.add(n); + } - // create an enumeration from the set and return - return Collections.enumeration(set); - } + // create an enumeration from the set and return + return Collections.enumeration(set); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/jsongraph/util/CommonUtility.java b/common-app-api/src/main/java/org/openecomp/sdc/common/jsongraph/util/CommonUtility.java index cbc5f0d56f..a4fc1b520e 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/jsongraph/util/CommonUtility.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/jsongraph/util/CommonUtility.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,57 +24,57 @@ import org.openecomp.sdc.common.log.wrappers.Logger; /** * Provides common utility: functionality, common fields and enumerations + * */ public class CommonUtility { - /** - * Provides list of logging level names - */ - public enum LogLevelEnum { - ERROR, - WARNING, - INFO, - DEBUG, - TRACE, - } - - /** - * Adds received message to log according to level in case if specified level is enabled - * - * @param logger - * @param logLevel - * @param format - * @param arguments - */ - public static void addRecordToLog(Logger logger, LogLevelEnum logLevel, String format, Object... arguments) { - switch (logLevel) { - case ERROR: - if (logger.isErrorEnabled()) { - logger.error(format, arguments); - } - break; - case WARNING: - if (logger.isWarnEnabled()) { - logger.warn(format, arguments); - } - break; - case INFO: - if (logger.isInfoEnabled()) { - logger.info(format, arguments); - } - break; - case DEBUG: - if (logger.isDebugEnabled()) { - logger.debug(format, arguments); - } - break; - case TRACE: - if (logger.isTraceEnabled()) { - logger.trace(format, arguments); - } - break; - default: - break; - } - } - + /** + * Provides list of logging level names + * + */ + public enum LogLevelEnum { + ERROR, + WARNING, + INFO, + DEBUG, + TRACE, + } + /** + * Adds received message to log according to level in case if specified level is enabled + * @param logger + * @param logLevel + * @param format + * @param arguments + */ + public static void addRecordToLog(Logger logger, LogLevelEnum logLevel, String format, Object... arguments ){ + switch(logLevel){ + case ERROR: + if(logger.isErrorEnabled()){ + logger.error(format, arguments); + } + break; + case WARNING: + if(logger.isWarnEnabled()){ + logger.warn(format, arguments); + } + break; + case INFO: + if(logger.isInfoEnabled()){ + logger.info(format, arguments); + } + break; + case DEBUG: + if(logger.isDebugEnabled()){ + logger.debug(format, arguments); + } + break; + case TRACE: + if(logger.isTraceEnabled()){ + logger.trace(format, arguments); + } + break; + default: + break; + } + } + } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/kpi/api/ASDCKpiApi.java b/common-app-api/src/main/java/org/openecomp/sdc/common/kpi/api/ASDCKpiApi.java index b1bd99ef76..65cf7161d4 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/kpi/api/ASDCKpiApi.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/kpi/api/ASDCKpiApi.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,43 +24,43 @@ import org.openecomp.sdc.common.log.wrappers.Logger; public class ASDCKpiApi { - private static Logger log = Logger.getLogger(ASDCKpiApi.class.getName()); + private static Logger log = Logger.getLogger(ASDCKpiApi.class.getName()); - /* Number of activated resource imports. */ - public static void countImportResourcesKPI() { - // TODO Auto-generated method stub - log.trace("Number of activated resource imports."); + /* Number of activated resource imports. */ + public static void countImportResourcesKPI() { + // TODO Auto-generated method stub + log.trace("Number of activated resource imports."); - } + } - /* Number of created resources. */ - public static void countCreatedResourcesKPI() { - // TODO Auto-generated method stub - log.trace("Number of created resources."); + /* Number of created resources. */ + public static void countCreatedResourcesKPI() { + // TODO Auto-generated method stub + log.trace("Number of created resources."); - } + } - /* Number of created services */ - public static void countCreatedServicesKPI() { - // TODO Auto-generated method stub - log.trace("Number of created services."); + /* Number of created services */ + public static void countCreatedServicesKPI() { + // TODO Auto-generated method stub + log.trace("Number of created services."); - } + } - /* - * Number of ASDC portal accesses ( number of activated user authorizations) - */ - public static void countUsersAuthorizations() { - // TODO Auto-generated method stub - log.trace("Number of activated distribution"); + /* + * Number of ASDC portal accesses ( number of activated user authorizations) + */ + public static void countUsersAuthorizations() { + // TODO Auto-generated method stub + log.trace("Number of activated distribution"); - } + } - /* Number of activated distribution */ - public static void countActivatedDistribution() { - // TODO Auto-generated method stub - log.trace("Number of activated distribution"); + /* Number of activated distribution */ + public static void countActivatedDistribution() { + // TODO Auto-generated method stub + log.trace("Number of activated distribution"); - } + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/listener/AppContextListener.java b/common-app-api/src/main/java/org/openecomp/sdc/common/listener/AppContextListener.java index dd05ee47ae..f5325a73e1 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/listener/AppContextListener.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/listener/AppContextListener.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -39,89 +39,89 @@ import java.util.jar.Manifest; public class AppContextListener implements ServletContextListener { - private static Logger log = Logger.getLogger(AppContextListener.class.getName()); + private static Logger log = Logger.getLogger(AppContextListener.class.getName()); - public void contextInitialized(ServletContextEvent context) { + public void contextInitialized(ServletContextEvent context) { - log.debug("ServletContextListener initialized "); + log.debug("ServletContextListener initialized "); - log.debug("After read values from Manifest {}", getManifestInfo(context.getServletContext())); + log.debug("After read values from Manifest {}", getManifestInfo(context.getServletContext())); - Map manifestAttr = getManifestInfo(context.getServletContext()); + Map manifestAttr = getManifestInfo(context.getServletContext()); - String appName = setAndGetAttributeInContext(context, manifestAttr, Constants.APPLICATION_NAME); - String appVersion = setAndGetAttributeInContext(context, manifestAttr, Constants.APPLICATION_VERSION); + String appName = setAndGetAttributeInContext(context, manifestAttr, Constants.APPLICATION_NAME); + String appVersion = setAndGetAttributeInContext(context, manifestAttr, Constants.APPLICATION_VERSION); - ExternalConfiguration.setAppName(appName); - ExternalConfiguration.setAppVersion(appVersion); - String configHome = System.getProperty(Constants.CONFIG_HOME); - ExternalConfiguration.setConfigDir(configHome); + ExternalConfiguration.setAppName(appName); + ExternalConfiguration.setAppVersion(appVersion); + String configHome = System.getProperty(Constants.CONFIG_HOME); + ExternalConfiguration.setConfigDir(configHome); - String appConfigDir = configHome + File.separator + appName; - // ChangeListener changeListener = new ChangeListener(); - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), - appConfigDir); + String appConfigDir = configHome + File.separator + appName; + // ChangeListener changeListener = new ChangeListener(); + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), + appConfigDir); - context.getServletContext().setAttribute(Constants.CONFIGURATION_SOURCE_ATTR, configurationSource); + context.getServletContext().setAttribute(Constants.CONFIGURATION_SOURCE_ATTR, configurationSource); - ExternalConfiguration.setConfigurationSource(configurationSource); + ExternalConfiguration.setConfigurationSource(configurationSource); - ExternalConfiguration.listenForChanges(); + ExternalConfiguration.listenForChanges(); - } + } - public void contextDestroyed(ServletContextEvent context) { + public void contextDestroyed(ServletContextEvent context) { - log.debug("ServletContextListener destroyed"); - ExternalConfiguration.stopListenForFileChanges(); - } + log.debug("ServletContextListener destroyed"); + ExternalConfiguration.stopListenForFileChanges(); + } - private String setAndGetAttributeInContext(ServletContextEvent context, Map manifestAttr, - String attr) { + private String setAndGetAttributeInContext(ServletContextEvent context, Map manifestAttr, + String attr) { - String name = manifestAttr.get(attr); - if (name != null) { - context.getServletContext().setAttribute(attr, name); - } + String name = manifestAttr.get(attr); + if (name != null) { + context.getServletContext().setAttribute(attr, name); + } - return name; - } + return name; + } - public static Map getManifestInfo(ServletContext application) { + public static Map getManifestInfo(ServletContext application) { - Map result = new HashMap<>(); - InputStream inputStream = null; - try { + Map result = new HashMap<>(); + InputStream inputStream = null; + try { - inputStream = application.getResourceAsStream("/META-INF/MANIFEST.MF"); + inputStream = application.getResourceAsStream("/META-INF/MANIFEST.MF"); - Manifest manifest = new Manifest(inputStream); + Manifest manifest = new Manifest(inputStream); - Attributes attr = manifest.getMainAttributes(); - String name = attr.getValue("Implementation-Title"); - if (name != null) { - result.put(Constants.APPLICATION_NAME, name); - } + Attributes attr = manifest.getMainAttributes(); + String name = attr.getValue("Implementation-Title"); + if (name != null) { + result.put(Constants.APPLICATION_NAME, name); + } - String version = attr.getValue("Implementation-Version"); - if (version != null) { - result.put(Constants.APPLICATION_VERSION, version); - } + String version = attr.getValue("Implementation-Version"); + if (version != null) { + result.put(Constants.APPLICATION_VERSION, version); + } - } catch (IOException e) { + } catch (IOException e) { - } finally { - if (inputStream != null) { - try { - inputStream.close(); - } catch (IOException e) { - log.info("close FileOutputStream failed - {}", e); - } - } - } + } finally { + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException e) { + log.info("close FileOutputStream failed - {}" , e); + } + } + } - return result; + return result; - } + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogConfiguration.java deleted file mode 100644 index 56fd7ad3a1..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogConfiguration.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.api; - -public interface ILogConfiguration { - String MDC_KEY_REQUEST_ID = "RequestId"; - String MDC_SERVICE_INSTANCE_ID = "ServiceInstanceId"; - String MDC_SERVICE_NAME = "ServiceName"; - String MDC_INSTANCE_UUID = "InstanceUUID"; - String MDC_SERVER_IP_ADDRESS = "ServerIPAddress"; - String MDC_SERVER_FQDN = "ServerFQDN"; - String MDC_REMOTE_HOST = "RemoteHost"; - String MDC_AUDIT_MESSAGE = "AuditMessage"; - String MDC_ALERT_SEVERITY = "AlertSeverity"; - String MDC_AUDIT_BEGIN_TIMESTAMP = "AuditBeginTimestamp"; - String MDC_METRIC_BEGIN_TIMESTAMP = "MetricBeginTimestamp"; - String MDC_END_TIMESTAMP = "EndTimestamp"; - String MDC_PARTNER_NAME = "PartnerName"; - String MDC_STATUS_CODE = "StatusCode"; - String MDC_RESPONSE_CODE = "ResponseCode"; - String MDC_RESPONSE_DESC = "ResponseDescription"; - String MDC_ELAPSED_TIME = "ElapsedTime"; - String MDC_PROCESS_KEY = "ProcessKey"; - String MDC_TARGET_ENTITY = "TargetEntity"; - String MDC_TARGET_SERVICE_NAME = "TargetServiceName"; - String MDC_TARGET_VIRTUAL_ENTITY = "TargetVirtualEntity"; - String MDC_ERROR_CATEGORY = "ErrorCategory"; - String MDC_ERROR_CODE = "ErrorCode"; - String MDC_ERROR_DESC = "ErrorDescription"; - String MDC_CLASS_NAME = "ClassName"; - String MDC_OPT_FIELD1 = "CustomField1"; - String MDC_OPT_FIELD2 = "CustomField2"; - String MDC_OPT_FIELD3 = "CustomField3"; - String MDC_OPT_FIELD4 = "CustomField4"; -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogFieldsHandler.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogFieldsHandler.java deleted file mode 100644 index 5b9728a6da..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogFieldsHandler.java +++ /dev/null @@ -1,131 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.api; - -import org.openecomp.sdc.common.log.enums.Severity; - -/** - * Created by dd4296 on 12/25/2017. - */ -public interface ILogFieldsHandler { - void startAuditTimer(); - - void startMetricTimer(); - - void stopAuditTimer(); - - void stopMetricTimer(); - - void setClassName(String className); - - void setServerFQDN(String serverFQDN); - - void setServerIPAddress(String serverIPAddress); - - // intended for setting this parameter in a given thread - void setServerFQDNInternally(); - - // intended for setting this parameter in a given thread - void setServerIPAddressInternally(); - - void setInstanceUUID(String instanceUUID); - - void setProcessKey(String processKey); - - void setAlertSeverity(Severity alertSeverity); - - void setOptCustomField1(String customField1); - - void setOptCustomField2(String customField2); - - void setOptCustomField3(String customField3); - - void setOptCustomField4(String customField4); - - void setKeyRequestId(String keyRequestId); - - void setRemoteHost(String remoteHost); - - void setServiceName(String serviceName); - - void setStatusCode(String statusCode); - - void setPartnerName(String partnerName); - - void setResponseCode(int responseCode); - - void setResponseDesc(String responseDesc); - - void setServiceInstanceId(String serviceInstanceId); - - void setTargetEntity(String targetEntity); - - void setTargetServiceName(String targetServiceName); - - void setTargetVirtualEntity(String targetVirtualEntity); - - void setErrorCode(int errorCode); - - void setErrorCategory(String errorCategory); - - String getErrorCode(); - - String getServiceName(); - - String getErrorCategory(); - - void clear(); - - boolean isMDCParamEmpty(String mdcKeyName); - - String getFqdn(); - - String getHostAddress(); - - String getKeyRequestId(); - - void removeStatusCode(); - - void removePartnerName(); - - void removeResponseCode(); - - void removeResponseDesc(); - - void removeServiceInstanceId(); - - void removeTargetEntity(); - - void removeTargetServiceName(); - - void removeTargetVirtualEntity(); - - void removeErrorCode(); - - void removeErrorCategory(); - - void removeErrorDescription(); - - void setAuditMessage(String message); - - String getAuditMessage(); - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogger.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogger.java deleted file mode 100644 index 175e7ec016..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogger.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.api; - -import org.openecomp.sdc.common.log.enums.LogLevel; - -import java.util.List; - -/** - * Created by dd4296 on 12/24/2017. - */ -public interface ILogger { - void log(LogLevel logLevel, String message); - - void log(LogLevel logLevel, String message, Object... params); - - void log(LogLevel logLevel, String message, Throwable throwable); - - List getMandatoryFields(); - - ILogger clear(); - - ILogger startTimer(); - - ILogger setKeyRequestId(String keyRequestId); -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandler.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandler.java deleted file mode 100644 index 9f7701bb49..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandler.java +++ /dev/null @@ -1,342 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.common.log.api.ILogConfiguration; -import org.openecomp.sdc.common.log.api.ILogFieldsHandler; -import org.openecomp.sdc.common.log.enums.Severity; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; - -import java.net.InetAddress; -import java.time.Duration; -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; - -import static java.lang.Integer.valueOf; - -public class LogFieldsMdcHandler implements ILogFieldsHandler { - - private static LogFieldsMdcHandler instanceMdcWrapper = new LogFieldsMdcHandler(); - - public static LogFieldsMdcHandler getInstance() { - return instanceMdcWrapper; - } - - private static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd HH:mm:ss.SSSz"; - private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_FORMAT_PATTERN); - protected static Logger log = LoggerFactory.getLogger(LogFieldsMdcHandler.class.getName()); - static String hostAddress; - protected static String fqdn; - - static { - try { - hostAddress = InetAddress.getLocalHost().getHostAddress(); - fqdn = InetAddress.getByName(hostAddress).getCanonicalHostName(); - } catch (Exception ex) { - log.error("failed to get machine parameters", ex); - } - } - - @Override - public void startAuditTimer() { - if (StringUtils.isEmpty(MDC.get(ILogConfiguration.MDC_AUDIT_BEGIN_TIMESTAMP))) { - MDC.put(ILogConfiguration.MDC_AUDIT_BEGIN_TIMESTAMP, generatedTimeNow()); - } - } - - @Override - public void startMetricTimer() { - if (StringUtils.isEmpty(MDC.get(ILogConfiguration.MDC_METRIC_BEGIN_TIMESTAMP))) { - MDC.put(ILogConfiguration.MDC_METRIC_BEGIN_TIMESTAMP, generatedTimeNow()); - } - } - - @Override - public void stopAuditTimer() { - //set start time if it is not set yet - startAuditTimer(); - MDC.put(ILogConfiguration.MDC_END_TIMESTAMP, generatedTimeNow()); - setElapsedTime(MDC.get(ILogConfiguration.MDC_AUDIT_BEGIN_TIMESTAMP)); - } - - @Override - public void stopMetricTimer() { - //set start time if it is not set yet - startMetricTimer(); - MDC.put(ILogConfiguration.MDC_END_TIMESTAMP, generatedTimeNow()); - setElapsedTime(MDC.get(ILogConfiguration.MDC_METRIC_BEGIN_TIMESTAMP)); - } - - @Override - public void setClassName(String className) { - MDC.put(ILogConfiguration.MDC_CLASS_NAME, className); - } - - @Override - public void setServerFQDN(String serverFQDN) { - MDC.put(ILogConfiguration.MDC_SERVER_FQDN, serverFQDN); - } - - @Override - public void setServerIPAddress(String serverIPAddress) { - MDC.put(ILogConfiguration.MDC_SERVER_IP_ADDRESS, serverIPAddress); - } - - @Override - public void setServerFQDNInternally() { - setServerFQDN(fqdn); - } - - @Override - public void setServerIPAddressInternally() { - setServerIPAddress(hostAddress); - } - - @Override - public void setInstanceUUID(String instanceUUID) { - MDC.put(ILogConfiguration.MDC_INSTANCE_UUID, instanceUUID); - } - - @Override - public void setProcessKey(String processKey) { - MDC.put(ILogConfiguration.MDC_PROCESS_KEY, processKey); - } - - @Override - public void setAlertSeverity(Severity alertSeverity) { - MDC.put(ILogConfiguration.MDC_ALERT_SEVERITY, String.valueOf(alertSeverity.getSeverityType())); - } - - @Override - public void setOptCustomField1(String customField1) { - MDC.put(ILogConfiguration.MDC_OPT_FIELD1, customField1); - } - - @Override - public void setOptCustomField2(String customField2) { - MDC.put(ILogConfiguration.MDC_OPT_FIELD2, customField2); - } - - @Override - public void setOptCustomField3(String customField3) { - MDC.put(ILogConfiguration.MDC_OPT_FIELD3, customField3); - } - - @Override - public void setOptCustomField4(String customField4) { - MDC.put(ILogConfiguration.MDC_OPT_FIELD4, customField4); - } - - @Override - public void setKeyRequestId(String keyRequestId) { - MDC.put(ILogConfiguration.MDC_KEY_REQUEST_ID, keyRequestId); // eg. servletRequest.getSession().getId() - } - - @Override - public void setRemoteHost(String remoteHost) { - MDC.put(ILogConfiguration.MDC_REMOTE_HOST, remoteHost); - } - - @Override - public void setServiceName(String serviceName) { - MDC.put(ILogConfiguration.MDC_SERVICE_NAME, serviceName); - } - - @Override - public void setStatusCode(String statusCode) { - MDC.put(ILogConfiguration.MDC_STATUS_CODE, statusCode); - } - - @Override - public void setPartnerName(String partnerName) { - MDC.put(ILogConfiguration.MDC_PARTNER_NAME, partnerName); - } - - @Override - public void setResponseCode(int responseCode) { - MDC.put(ILogConfiguration.MDC_RESPONSE_CODE, Integer.toString(responseCode)); - } - - @Override - public void setResponseDesc(String responseDesc) { - MDC.put(ILogConfiguration.MDC_RESPONSE_DESC, responseDesc); - } - - @Override - public void setServiceInstanceId(String serviceInstanceId) { - MDC.put(ILogConfiguration.MDC_SERVICE_INSTANCE_ID, serviceInstanceId); - } - - @Override - public void setTargetEntity(String targetEntity) { - MDC.put(ILogConfiguration.MDC_TARGET_ENTITY, targetEntity); - } - - @Override - public void setTargetServiceName(String targetServiceName) { - MDC.put(ILogConfiguration.MDC_TARGET_SERVICE_NAME, targetServiceName); - } - - @Override - public void setTargetVirtualEntity(String targetVirtualEntity) { - MDC.put(ILogConfiguration.MDC_TARGET_VIRTUAL_ENTITY, targetVirtualEntity); - } - - @Override - public void setErrorCode(int errorCode) { - MDC.put(ILogConfiguration.MDC_ERROR_CODE, valueOf(errorCode).toString()); - } - - @Override - public void setErrorCategory(String errorCategory) { - MDC.put(ILogConfiguration.MDC_ERROR_CATEGORY, errorCategory); - } - - @Override - public String getErrorCode() { - return MDC.get(ILogConfiguration.MDC_ERROR_CODE); - } - - @Override - public String getServiceName() { - return MDC.get(ILogConfiguration.MDC_SERVICE_NAME); - } - - @Override - public String getErrorCategory() { - return MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY); - } - - @Override - public void clear() { - MDC.clear(); - } - - @Override - public boolean isMDCParamEmpty(String mdcKeyName) { - return StringUtils.isEmpty(MDC.get(mdcKeyName)); - } - - @Override - public String getFqdn() { - return fqdn; - } - - @Override - public String getHostAddress() { - return hostAddress; - } - - @Override - public String getKeyRequestId() { - return MDC.get(ILogConfiguration.MDC_KEY_REQUEST_ID); - } - - @Override - public void removeStatusCode() { - MDC.remove(ILogConfiguration.MDC_STATUS_CODE); - } - - @Override - public void removePartnerName() { - MDC.remove(ILogConfiguration.MDC_PARTNER_NAME); - } - - @Override - public void removeResponseCode() { - MDC.remove(ILogConfiguration.MDC_RESPONSE_CODE); - } - - @Override - public void removeResponseDesc() { - MDC.remove(ILogConfiguration.MDC_RESPONSE_DESC); - } - - @Override - public void removeServiceInstanceId() { - MDC.remove(ILogConfiguration.MDC_SERVICE_INSTANCE_ID); - } - - @Override - public void removeTargetEntity() { - MDC.remove(ILogConfiguration.MDC_TARGET_ENTITY); - } - - @Override - public void removeTargetServiceName() { - MDC.remove(ILogConfiguration.MDC_TARGET_SERVICE_NAME); - } - - @Override - public void removeTargetVirtualEntity() { - MDC.remove(ILogConfiguration.MDC_TARGET_VIRTUAL_ENTITY); - } - - @Override - public void removeErrorCode() { - MDC.remove(ILogConfiguration.MDC_ERROR_CODE); - } - - @Override - public void removeErrorCategory() { - MDC.remove(ILogConfiguration.MDC_ERROR_CATEGORY); - } - - @Override - public void removeErrorDescription() { - MDC.remove(ILogConfiguration.MDC_ERROR_DESC); - } - - @Override - public void setAuditMessage(String message) { - MDC.put(ILogConfiguration.MDC_AUDIT_MESSAGE, message); - } - - @Override - public String getAuditMessage() { - return MDC.get(ILogConfiguration.MDC_AUDIT_MESSAGE); - } - - private void setElapsedTime(String beginTimestamp) { - try { - final LocalDateTime startTime = LocalDateTime.parse(beginTimestamp, dateTimeFormatter); - final LocalDateTime endTime = LocalDateTime.parse(MDC.get(ILogConfiguration.MDC_END_TIMESTAMP), dateTimeFormatter); - final Duration timeDifference = Duration.between(startTime, endTime); - - MDC.put(ILogConfiguration.MDC_ELAPSED_TIME, String.valueOf(timeDifference.toMillis())); - - } catch (Exception ex) { - log.error("failed to calculate elapsed time", ex); - } - } - - private String generatedTimeNow() { - return dateTimeFormatter - .withZone(ZoneOffset.UTC) - .format(Instant.now()); - } - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerAudit.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerAudit.java deleted file mode 100644 index 247bed2773..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerAudit.java +++ /dev/null @@ -1,187 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - - -import org.openecomp.sdc.common.log.api.ILogConfiguration; -import org.openecomp.sdc.common.log.api.ILogFieldsHandler; -import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; -import org.openecomp.sdc.common.log.enums.LogMarkers; -import org.openecomp.sdc.common.log.enums.Severity; -import org.openecomp.sdc.common.log.enums.StatusCode; -import org.slf4j.Logger; -import org.slf4j.MDC; -import org.slf4j.MarkerFactory; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public class LoggerAudit extends LoggerBase { - private static final int STATUS_MAJOR_PART_MASK = 100; - private static ArrayList mandatoryFields = new ArrayList<>(Arrays.asList( - ILogConfiguration.MDC_AUDIT_BEGIN_TIMESTAMP, - ILogConfiguration.MDC_END_TIMESTAMP, - ILogConfiguration.MDC_KEY_REQUEST_ID, - ILogConfiguration.MDC_SERVICE_NAME, - ILogConfiguration.MDC_PARTNER_NAME, - ILogConfiguration.MDC_STATUS_CODE, - ILogConfiguration.MDC_RESPONSE_CODE, - ILogConfiguration.MDC_SERVICE_INSTANCE_ID, - ILogConfiguration.MDC_RESPONSE_DESC, - ILogConfiguration.MDC_ELAPSED_TIME, - ILogConfiguration.MDC_SERVER_IP_ADDRESS, - ILogConfiguration.MDC_SERVER_FQDN)); - - private static ArrayList optionalFields = new ArrayList<>(Arrays.asList( - ILogConfiguration.MDC_INSTANCE_UUID, - ILogConfiguration.MDC_ALERT_SEVERITY, - ILogConfiguration.MDC_REMOTE_HOST, - ILogConfiguration.MDC_CLASS_NAME, - ILogConfiguration.MDC_PROCESS_KEY, - ILogConfiguration.MDC_OPT_FIELD1, - ILogConfiguration.MDC_OPT_FIELD2, - ILogConfiguration.MDC_OPT_FIELD3, - ILogConfiguration.MDC_OPT_FIELD4)); - - LoggerAudit(ILogFieldsHandler ecompMdcWrapper, Logger logger) { - super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.AUDIT_MARKER.text()), logger); - //put the remote host and FQDN values from another thread if they are set - ecompMdcWrapper.setServerIPAddressInternally(); - ecompMdcWrapper.setServerFQDNInternally(); - } - - @Override - public LoggerAudit startTimer() { - ecompLogFieldsHandler.startAuditTimer(); - return this; - } - - public LoggerAudit stopTimer() { - ecompLogFieldsHandler.stopAuditTimer(); - return this; - } - - public LoggerAudit setInstanceUUID(String instanceUUID) { - ecompLogFieldsHandler.setInstanceUUID(instanceUUID); - return this; - } - - public LoggerAudit setOptClassName(String className) { - MDC.put("ClassName", className); - return this; - } - - public LoggerAudit setOptProcessKey(String processKey) { - ecompLogFieldsHandler.setProcessKey(processKey); - return this; - } - - public LoggerAudit setOptAlertSeverity(Severity alertSeverity) { - ecompLogFieldsHandler.setAlertSeverity(alertSeverity); - return this; - } - - // log optional parameter - public LoggerAudit setOptCustomField1(String customField1) { - ecompLogFieldsHandler.setOptCustomField1(customField1); - return this; - } - - // log optional parameter - public LoggerAudit setOptCustomField2(String customField2) { - ecompLogFieldsHandler.setOptCustomField2(customField2); - return this; - } - - // log optional parameter - public LoggerAudit setOptCustomField3(String customField3) { - ecompLogFieldsHandler.setOptCustomField3(customField3); - return this; - } - - public LoggerAudit setOptCustomField4(String customField4) { - ecompLogFieldsHandler.setOptCustomField4(customField4); - return this; - } - - @Override - public LoggerAudit setKeyRequestId(String keyRequestId) { - return (LoggerAudit) super.setKeyRequestId(keyRequestId); - } - - public LoggerAudit setRemoteHost(String remoteHost) { - ecompLogFieldsHandler.setRemoteHost(remoteHost); - return this; - } - - public LoggerAudit setServiceName(String serviceName) { - ecompLogFieldsHandler.setServiceName(serviceName); - return this; - } - - public LoggerAudit setStatusCode(String statusCode) { - // status code is either success (COMPLETE) or failure (ERROR) of the request. - String respStatus = Integer.parseInt(statusCode) / STATUS_MAJOR_PART_MASK == 2 ? StatusCode.COMPLETE.getStatusCodeEnum() : StatusCode.ERROR.getStatusCodeEnum(); - ecompLogFieldsHandler.setStatusCode(respStatus); - return this; - } - - public LoggerAudit setPartnerName(String partnerName) { - ecompLogFieldsHandler.setPartnerName(partnerName); - return this; - } - - public LoggerAudit setResponseCode(EcompLoggerErrorCode responseCode) { - ecompLogFieldsHandler.setResponseCode(responseCode.getErrorCode()); - return this; - } - - public LoggerAudit setResponseDesc(String responseDesc) { - ecompLogFieldsHandler.setResponseDesc(responseDesc); - return this; - } - - public LoggerAudit setOptServiceInstanceId(String serviceInstanceId) { - ecompLogFieldsHandler.setServiceInstanceId(serviceInstanceId); - return this; - } - - public String getAuditMessage() { - return ecompLogFieldsHandler.getAuditMessage(); - } - - - @Override - public List getMandatoryFields() { - return Collections.unmodifiableList(mandatoryFields); - } - - @Override - public LoggerAudit clear() { - super.clear(); - ecompLogFieldsHandler.setServerFQDNInternally(); - ecompLogFieldsHandler.setServerIPAddressInternally(); - return this; - } - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerBase.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerBase.java deleted file mode 100644 index 1c14d24da8..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerBase.java +++ /dev/null @@ -1,166 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - -import com.google.common.annotations.VisibleForTesting; -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.common.log.api.ILogFieldsHandler; -import org.openecomp.sdc.common.log.api.ILogger; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.openecomp.sdc.common.log.enums.LogMarkers; -import org.openecomp.sdc.common.util.ThreadLocalsHolder; -import org.slf4j.Logger; -import org.slf4j.Marker; -import org.slf4j.MarkerFactory; - -import java.util.Arrays; -import java.util.List; - - -/** - * Created by mm288v on 12/27/2017. - * This class holds the common behavior of all Loger-Typed classes. - * The Concrete loggers shoudl derive from this one. - */ -public abstract class LoggerBase implements ILogger { - private final Logger myLogger; - private final Marker myMarker; - final ILogFieldsHandler ecompLogFieldsHandler; - private static final String MISSING_LOG_FIELDS_MESSAGE = "mandatory parameters for ECOMP logging, missing fields: %s, original message: %s"; - - LoggerBase(ILogFieldsHandler ecompLogFieldsHandler, Marker marker, Logger logger) { - this.ecompLogFieldsHandler = ecompLogFieldsHandler; - this.myMarker = marker; - this.myLogger = logger; - setKeyRequestIdIfNotSetYet(); - } - - void setKeyRequestIdIfNotSetYet() { - if (StringUtils.isEmpty(ecompLogFieldsHandler.getKeyRequestId())) { - setKeyRequestId(ThreadLocalsHolder.getUuid()); - } - } - - private void validateMandatoryFields(String originMsg) { - // this method only checks if the mandatory fields have been initialized - String filedNameThatHasNotBeenInitialized = checkMandatoryFieldsExistInMDC(); - - if (myLogger.isDebugEnabled() && !"".equalsIgnoreCase(filedNameThatHasNotBeenInitialized)) { - myLogger.debug(MarkerFactory.getMarker(LogMarkers.DEBUG_MARKER.text()), - String.format(MISSING_LOG_FIELDS_MESSAGE, filedNameThatHasNotBeenInitialized, originMsg)); - } - } - - @VisibleForTesting - String checkMandatoryFieldsExistInMDC() { - // this method returns a String of uninitialised fields - StringBuilder missingFields = new StringBuilder(); - getMandatoryFields().forEach(field -> { - if (ecompLogFieldsHandler.isMDCParamEmpty(field)) { - missingFields.append(field).append(" "); - } - }); - return missingFields.toString(); - } - - public abstract List getMandatoryFields(); - - protected String convertExceptionStackToString(Exception ex) { - StringBuilder stackTrack = new StringBuilder(); - Arrays.asList(ex.getStackTrace()).forEach(item -> stackTrack.append(item.toString()).append("\n")); - return stackTrack.toString(); - } - - @Override - public void log(LogLevel logLevel, String message) { - log(logLevel, message, (Object) null); - } - - @Override - public void log(LogLevel logLevel, String message, Object... params) { - validateMandatoryFields(message); - - switch (logLevel) { - case ERROR: - case FATAL: //TODO check how to log "FATAL" word - myLogger.error(myMarker, message, params); - break; - case WARN: - myLogger.warn(myMarker, message, params); - break; - case INFO: - myLogger.info(myMarker, message, params); - break; - case DEBUG: - myLogger.debug(myMarker, message, params); - break; - case TRACE: - myLogger.trace(myMarker, message, params); - break; - default: - break; - } - } - - @Override - public void log(LogLevel logLevel, String message, Throwable throwable) { - validateMandatoryFields(message); - - switch (logLevel) { - case ERROR: - case FATAL: //TODO check how to log "FATAL" word - myLogger.error(myMarker, createErrorMessage(message, throwable)); - break; - case WARN: - myLogger.warn(myMarker, createErrorMessage(message, throwable)); - break; - case INFO: - myLogger.info(myMarker, createErrorMessage(message, throwable)); - break; - case DEBUG: - myLogger.debug(myMarker, message, throwable); - break; - case TRACE: - myLogger.trace(myMarker, message, throwable); - break; - default: - break; - } - } - - String createErrorMessage(String message, Throwable throwable) { - return String.format("%s: %s", message, throwable.getLocalizedMessage()); - } - - - @Override - public ILogger clear() { - ecompLogFieldsHandler.clear(); - return this; - } - - @Override - public ILogger setKeyRequestId(String keyRequestId) { - ecompLogFieldsHandler.setKeyRequestId(keyRequestId); - return this; - } - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerDebug.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerDebug.java deleted file mode 100644 index d7d48274c8..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerDebug.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - -import org.openecomp.sdc.common.log.api.ILogConfiguration; -import org.openecomp.sdc.common.log.api.ILogFieldsHandler; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.openecomp.sdc.common.log.enums.LogMarkers; -import org.slf4j.Logger; -import org.slf4j.MarkerFactory; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class LoggerDebug extends LoggerBase { - - private static ArrayList mandatoryFields = new ArrayList<>(Arrays.asList(ILogConfiguration.MDC_KEY_REQUEST_ID)); - - LoggerDebug(ILogFieldsHandler ecompMdcWrapper, Logger logger) { - super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.DEBUG_MARKER.text()), logger); - } - - @Override - public LoggerDebug clear() { - //nothing to clean up - return this; - } - - @Override - public void log(LogLevel logLevel, String message, Object... params) { - setKeyRequestIdIfNotSetYet(); - super.log(logLevel, message, params); - } - - @Override - public void log(LogLevel logLevel, String message, Throwable throwable) { - setKeyRequestIdIfNotSetYet(); - super.log(logLevel, message, throwable); - } - - @Override - public void log(LogLevel logLevel, String message) { - setKeyRequestIdIfNotSetYet(); - super.log(logLevel, message); - } - - @Override - public LoggerDebug startTimer() { - return this; - } - - @Override - public List getMandatoryFields() { - return mandatoryFields; - } -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerError.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerError.java deleted file mode 100644 index 835c5793ba..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerError.java +++ /dev/null @@ -1,151 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.common.config.EcompErrorConfiguration; -import org.openecomp.sdc.common.log.api.ILogConfiguration; -import org.openecomp.sdc.common.log.api.ILogFieldsHandler; -import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.openecomp.sdc.common.log.enums.LogMarkers; -import org.slf4j.Logger; -import org.slf4j.MarkerFactory; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public class LoggerError extends LoggerBase { - private static ArrayList mandatoryFields = new ArrayList<>(Arrays.asList( - ILogConfiguration.MDC_KEY_REQUEST_ID, - ILogConfiguration.MDC_SERVICE_NAME, - ILogConfiguration.MDC_ERROR_CATEGORY, - ILogConfiguration.MDC_ERROR_CODE)); - - public static final String defaultServiceName = "SDC catalog"; - - LoggerError(ILogFieldsHandler ecompMdcWrapper, Logger logger) { - super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.ERROR_MARKER.text()), logger); - } - - @Override - public List getMandatoryFields() { - return Collections.unmodifiableList(mandatoryFields); - } - - @Override - public LoggerError setKeyRequestId(String keyRequestId) { - return (LoggerError) super.setKeyRequestId(keyRequestId); - } - - @Override - public LoggerError startTimer() { - return this; - } - - @Override - public LoggerError clear() { - ecompLogFieldsHandler.removeErrorCategory(); - ecompLogFieldsHandler.removeErrorDescription(); - ecompLogFieldsHandler.removeErrorCode(); - return this; - } - - public void log(LogLevel logLevel, - EcompLoggerErrorCode errorCodeEnum, - String serviceName, - String targetEntity, - String message, Object... params) { - fillFieldsBeforeLogging(logLevel, errorCodeEnum, serviceName, targetEntity); - super.log(logLevel, message, params); - } - - private void fillFieldsBeforeLogging(LogLevel logLevel, EcompLoggerErrorCode errorCodeEnum, String serviceName, String targetEntity) { - clear(); - ecompLogFieldsHandler.setErrorCode(errorCodeEnum.getErrorCode()); - ecompLogFieldsHandler.setErrorCategory(logLevel.name()); - if (!StringUtils.isEmpty(targetEntity)) { - //avoid overriding this parameter in MDC - ecompLogFieldsHandler.setTargetEntity(targetEntity); - } - if (StringUtils.isEmpty(ecompLogFieldsHandler.getServiceName())) { - ecompLogFieldsHandler.setServiceName(serviceName); - } - setKeyRequestIdIfNotSetYet(); - } - - public void log(EcompErrorConfiguration.EcompErrorSeverity errorSeverity, - EcompLoggerErrorCode errorCodeEnum, - String serviceName, - String targetEntity, - String message, Object... params) { - log(convertFromSeverityErrorLevel(errorSeverity), errorCodeEnum, serviceName, targetEntity, message, params); - } - - public void log(LogLevel logLevel, - EcompLoggerErrorCode errorCodeEnum, - String serviceName, - String message, Object... params) { - log(logLevel, errorCodeEnum, serviceName, null, message, params); - } - - public void log(LogLevel logLevel, - EcompLoggerErrorCode errorCodeEnum, - String serviceName, - String message) { - log(logLevel, errorCodeEnum, serviceName, message); - } - - @Override - public void log(LogLevel logLevel, String message, Object... params) { - log(logLevel, EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, defaultServiceName, null, message, params); - } - - public void log(LogLevel logLevel, String message, Throwable throwable) { - log(logLevel, createErrorMessage(message, throwable)); - } - - public void log(LogLevel logLevel, String message) { - log(logLevel, EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, defaultServiceName, null, message); - } - - public void logInfo(LogLevel logLevel, String message, Object... params) { - log(logLevel, EcompLoggerErrorCode.SUCCESS, defaultServiceName, null, message, params); - } - - private LogLevel convertFromSeverityErrorLevel(EcompErrorConfiguration.EcompErrorSeverity severityLevel) { - switch (severityLevel) { - case INFO: - return LogLevel.INFO; - case FATAL: - return LogLevel.FATAL; - case ERROR: - return LogLevel.ERROR; - case WARN: - return LogLevel.WARN; - default: - return LogLevel.ERROR; - } - } - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerFactory.java deleted file mode 100644 index 41c76a3ebe..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerFactory.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - -import org.slf4j.Logger; - -/** - * Created by dd4296 on 12/26/2017. - * this factory helps decouple the classes for Stopwatch and LogFieldsMdcHandler from - * the EcompLogger classes - */ -public class LoggerFactory { - - private LoggerFactory() { - } - - @SuppressWarnings("unchecked") - public static V getLogger(Class type, Logger logger) { - - if (type.isAssignableFrom(LoggerAudit.class)) { - return (V) new LoggerAudit(new LogFieldsMdcHandler(), logger); - } - - if (type.isAssignableFrom(LoggerDebug.class)) { - return (V) new LoggerDebug(new LogFieldsMdcHandler(), logger); - } - - if (type.isAssignableFrom(LoggerMetric.class)) { - return (V) new LoggerMetric(new LogFieldsMdcHandler(), logger); - } - - if (type.isAssignableFrom(LoggerError.class)) { - return (V) new LoggerError(new LogFieldsMdcHandler(), logger); - } - - return null; - } - - @SuppressWarnings("unchecked") - public static V getMdcLogger(Class type, Logger logger) { - - if (type.isAssignableFrom(LoggerAudit.class)) { - return (V) new LoggerAudit(LogFieldsMdcHandler.getInstance(), logger); - } - - if (type.isAssignableFrom(LoggerDebug.class)) { - return (V) new LoggerDebug(LogFieldsMdcHandler.getInstance(), logger); - } - - if (type.isAssignableFrom(LoggerMetric.class)) { - return (V) new LoggerMetric(LogFieldsMdcHandler.getInstance(), logger); - } - - if (type.isAssignableFrom(LoggerError.class)) { - return (V) new LoggerError(LogFieldsMdcHandler.getInstance(), logger); - } - - return null; - } -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerMetric.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerMetric.java deleted file mode 100644 index f777244952..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerMetric.java +++ /dev/null @@ -1,252 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - -import org.openecomp.sdc.common.log.api.ILogFieldsHandler; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.openecomp.sdc.common.log.enums.LogMarkers; -import org.openecomp.sdc.common.log.enums.Severity; -import org.slf4j.Logger; -import org.slf4j.MarkerFactory; - -import javax.ws.rs.core.Response; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_ALERT_SEVERITY; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_CLASS_NAME; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_ELAPSED_TIME; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_END_TIMESTAMP; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_INSTANCE_UUID; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_KEY_REQUEST_ID; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_METRIC_BEGIN_TIMESTAMP; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_OPT_FIELD1; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_OPT_FIELD2; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_OPT_FIELD3; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_OPT_FIELD4; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_PARTNER_NAME; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_PROCESS_KEY; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_REMOTE_HOST; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_RESPONSE_CODE; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_RESPONSE_DESC; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_SERVER_FQDN; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_SERVER_IP_ADDRESS; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_SERVICE_INSTANCE_ID; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_SERVICE_NAME; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_STATUS_CODE; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_TARGET_ENTITY; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_TARGET_SERVICE_NAME; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_TARGET_VIRTUAL_ENTITY; - - -public class LoggerMetric extends LoggerBase { - private static ArrayList mandatoryFields = new ArrayList<>(Arrays.asList( - MDC_METRIC_BEGIN_TIMESTAMP, - MDC_END_TIMESTAMP, - MDC_KEY_REQUEST_ID, - MDC_SERVICE_NAME, - MDC_PARTNER_NAME, - MDC_STATUS_CODE, - MDC_RESPONSE_CODE, - MDC_SERVICE_INSTANCE_ID, - MDC_RESPONSE_DESC, - MDC_ELAPSED_TIME, - MDC_TARGET_ENTITY, - MDC_TARGET_SERVICE_NAME, - MDC_TARGET_VIRTUAL_ENTITY, - MDC_SERVER_IP_ADDRESS, - MDC_SERVER_FQDN)); - - private static ArrayList optionalFields = new ArrayList<>(Arrays.asList( - MDC_INSTANCE_UUID, - MDC_ALERT_SEVERITY, - MDC_REMOTE_HOST, - MDC_CLASS_NAME, - MDC_PROCESS_KEY, - MDC_OPT_FIELD1, - MDC_OPT_FIELD2, - MDC_OPT_FIELD3, - MDC_OPT_FIELD4)); - - LoggerMetric(ILogFieldsHandler ecompMdcWrapper, Logger logger) { - super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.METRIC_MARKER.text()), logger); - //put the remote host and FQDN values from another thread if they are set - ecompMdcWrapper.setServerIPAddressInternally(); - ecompMdcWrapper.setServerFQDNInternally(); - } - - public void log(Response.StatusType statusInfo, - String className, - LogLevel logLevel, - Severity securityLevel, - String message) { - log(statusInfo, className, logLevel, securityLevel, message); - } - - @Override - public void log(LogLevel logLevel, String message) { - setKeyRequestIdIfNotSetYet(); - log(logLevel, message, (Object) null); - } - - @Override - public LoggerMetric startTimer() { - clear(); - ecompLogFieldsHandler.startMetricTimer(); - return this; - } - - public LoggerMetric stopTimer() { - ecompLogFieldsHandler.stopMetricTimer(); - return this; - } - - @Override - public LoggerMetric setKeyRequestId(String keyRequestId) { - return (LoggerMetric) super.setKeyRequestId(keyRequestId); - } - - @Override - public List getMandatoryFields() { - return mandatoryFields; - } - - @Override - public LoggerMetric clear() { - ecompLogFieldsHandler.removeTargetEntity(); - ecompLogFieldsHandler.removeTargetServiceName(); - ecompLogFieldsHandler.removeResponseCode(); - ecompLogFieldsHandler.removeResponseDesc(); - ecompLogFieldsHandler.removeStatusCode(); - return this; - } - - // automatic parameter this is optional - public LoggerMetric setAutoServerFQDN(String serverFQDN) { - ecompLogFieldsHandler.setServerFQDN(serverFQDN); - return this; - } - - // automatic parameter this is optional - public LoggerMetric setAutoServerIPAddress(String serverIPAddress) { - ecompLogFieldsHandler.setServerIPAddress(serverIPAddress); - return this; - } - - public LoggerMetric setInstanceUUID(String instanceUUID) { - ecompLogFieldsHandler.setInstanceUUID(instanceUUID); - return this; - } - - // log optional parameter - public LoggerMetric setOptProcessKey(String processKey) { - ecompLogFieldsHandler.setProcessKey(processKey); - return this; - } - - // log optional parameter - public LoggerMetric setOptAlertSeverity(Severity alertSeverity) { - ecompLogFieldsHandler.setAlertSeverity(alertSeverity); - return this; - } - - // log optional parameter - public LoggerMetric setOptCustomField1(String customField1) { - ecompLogFieldsHandler.setOptCustomField1(customField1); - return this; - } - - // log optional parameter - public LoggerMetric setOptCustomField2(String customField2) { - ecompLogFieldsHandler.setOptCustomField2(customField2); - return this; - } - - // log optional parameter - public LoggerMetric setOptCustomField3(String customField3) { - ecompLogFieldsHandler.setOptCustomField3(customField3); - return this; - } - - // log optional parameter - public LoggerMetric setOptCustomField4(String customField4) { - ecompLogFieldsHandler.setOptCustomField4(customField4); - return this; - } - - public LoggerMetric setRemoteHost(String remoteHost) { - ecompLogFieldsHandler.setRemoteHost(remoteHost); - return this; - } - - public LoggerMetric setServiceName(String serviceName) { - ecompLogFieldsHandler.setServiceName(serviceName); - return this; - } - - public LoggerMetric setStatusCode(String statusCode) { - ecompLogFieldsHandler.setStatusCode(statusCode); - return this; - } - - public LoggerMetric setPartnerName(String partnerName) { - ecompLogFieldsHandler.setPartnerName(partnerName); - return this; - } - - public LoggerMetric setResponseCode(int responseCode) { - ecompLogFieldsHandler.setResponseCode(responseCode); - return this; - } - - public LoggerMetric setResponseDesc(String responseDesc) { - ecompLogFieldsHandler.setResponseDesc(responseDesc); - return this; - } - - public LoggerMetric setOptServiceInstanceId(String serviceInstanceId) { - ecompLogFieldsHandler.setServiceInstanceId(serviceInstanceId); - return this; - } - - public LoggerMetric setOptClassName(String className) { - ecompLogFieldsHandler.setClassName(className); - return this; - } - - public LoggerMetric setTargetEntity(String targetEntity) { - ecompLogFieldsHandler.setTargetEntity(targetEntity); - return this; - } - - public LoggerMetric setTargetServiceName(String targetServiceName) { - ecompLogFieldsHandler.setTargetServiceName(targetServiceName); - return this; - } - - public LoggerMetric setTargetVirtualEntity(String targetVirtualEntity) { - ecompLogFieldsHandler.setTargetVirtualEntity(targetVirtualEntity); - return this; - } - - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/EcompLoggerErrorCode.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/EcompLoggerErrorCode.java deleted file mode 100644 index ce28ca0359..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/EcompLoggerErrorCode.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.enums; - -import java.util.Arrays; -import java.util.Optional; - -/** - * Created by dd4296 on 12/26/2017. - */ -public enum EcompLoggerErrorCode { - SUCCESS(0), - PERMISSION_ERROR(100), - AVAILABILITY_TIMEOUTS_ERROR(200), - DATA_ERROR(300), - SCHEMA_ERROR(400), - BUSINESS_PROCESS_ERROR(500), - UNKNOWN_ERROR(900); - - private static final int ERROR_CODE_SUBSTRING = 3; - private int errorCode; - - EcompLoggerErrorCode(int errorCode) { - this.errorCode = errorCode; - } - - public int getErrorCode() { - return errorCode; - } - - public static EcompLoggerErrorCode getByValue(String ecompErrorCode) { - String errorPrefix = parseCode(ecompErrorCode); - Optional optionalCode = Arrays.stream(values()).filter(v -> isCode(v, errorPrefix)).findFirst(); - return optionalCode.orElse(UNKNOWN_ERROR); - } - - private static boolean isCode(EcompLoggerErrorCode ecompLoggerErrorCode, String errorPrefix) { - return String.valueOf(ecompLoggerErrorCode.getErrorCode()).contains(errorPrefix); - } - - private static String parseCode(String errorCode) { - try { - return errorCode.substring("E_".length(), ERROR_CODE_SUBSTRING); - } catch (StringIndexOutOfBoundsException ex) { - return UNKNOWN_ERROR.name(); - } - } - - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/LogLevel.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/LogLevel.java deleted file mode 100644 index b04477bc82..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/LogLevel.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.enums; - -/** - * Created by dd4296 on 12/14/2017. - */ -public enum LogLevel { - INFO, - WARN, - DEBUG, - TRACE, - ERROR, - FATAL -} - diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/LogMarkers.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/LogMarkers.java deleted file mode 100644 index 3e99b729dd..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/LogMarkers.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.enums; - -/** - * Created by mm288v on 12/27/2017. - * This enum reflects the Marker text in logback.xml file per each ecomp marker - */ -public enum LogMarkers { - DEBUG_MARKER("DEBUG_MARKER"), - ERROR_MARKER("ERROR_MARKER"), - AUDIT_MARKER("AUDIT_MARKER"), - METRIC_MARKER("METRICS"); - - private String text; - - LogMarkers(String text) { - this.text = text; - } - - public String text() { - return text; - } - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/Severity.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/Severity.java deleted file mode 100644 index 9a5e8d92ab..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/Severity.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.enums; - -/** - * Created by dd4296 on 12/14/2017. - */ -public enum Severity { - OK(0), - WARNING(1), - CRITICAL(2), - DOWN(3), - UNREACHABLE(4); - - private int severityType; - - Severity(int serveryType) { - this.severityType = serveryType; - } - - public int getSeverityType() { - return severityType; - } -} - diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/StatusCode.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/StatusCode.java deleted file mode 100644 index 6489916a4c..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/StatusCode.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.enums; - -public enum StatusCode { - ERROR("ERROR"), - COMPLETE("COMPLETE"); - - private String statusCode; - - StatusCode(String statusCode) { - this.statusCode = statusCode; - } - - public String getStatusCodeEnum() { - return statusCode; - } -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogRequestInterceptor.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogRequestInterceptor.java new file mode 100644 index 0000000000..b51d7f1ba9 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogRequestInterceptor.java @@ -0,0 +1,60 @@ +package org.openecomp.sdc.common.log.interceptors; + +import org.apache.http.*; +import org.apache.http.protocol.HttpContext; +import org.onap.logging.filter.base.AbstractMetricLogFilter; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler; + +import java.io.IOException; +import java.net.URI; + +public class ApacheClientLogRequestInterceptor extends AbstractMetricLogFilter implements HttpRequestInterceptor { + + private String previousInvocationId; + + @Override + protected void addHeader(HttpMessage httpMessage, String s, String s1) { + httpMessage.addHeader(s, s1); + } + + @Override + protected String getTargetServiceName(HttpRequest httpRequest) { + return httpRequest.getRequestLine().getUri(); + } + + @Override + protected String getServiceName(HttpRequest httpRequest) { + return URI.create(httpRequest.getRequestLine().getUri()).getPath(); + } + + @Override + protected int getHttpStatusCode(HttpResponse httpResponse) { + return httpResponse.getStatusLine().getStatusCode(); + } + + @Override + protected String getResponseCode(HttpResponse httpResponse) { + return String.valueOf(httpResponse.getStatusLine().getStatusCode()); + } + + @Override + protected String getTargetEntity(HttpRequest httpRequest) { + //fallback to default value that provided by AbstractMetricLogFilter + return null; + } + + @Override + protected void additionalPre(HttpRequest httpRequest, HttpMessage httpMessage) { + String outgoingInvocationId = httpMessage.getFirstHeader(ONAPLogConstants.Headers.INVOCATION_ID).getValue(); + LogFieldsMdcHandler.getInstance().setOutgoingInvocationId(outgoingInvocationId); + LogFieldsMdcHandler.getInstance().setKeyInvocationId(previousInvocationId); + } + + + @Override + public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException { + previousInvocationId = LogFieldsMdcHandler.getInstance().getKeyInvocationId(); + super.pre(httpRequest, httpRequest); + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogResponseInterceptor.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogResponseInterceptor.java new file mode 100644 index 0000000000..d7f8b952f0 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogResponseInterceptor.java @@ -0,0 +1,49 @@ +package org.openecomp.sdc.common.log.interceptors; + +import org.apache.http.*; +import org.apache.http.protocol.HttpContext; +import org.onap.logging.filter.base.AbstractMetricLogFilter; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler; + +import java.io.IOException; +import java.net.URI; + +public class ApacheClientLogResponseInterceptor extends AbstractMetricLogFilter implements HttpResponseInterceptor { + + @Override + protected void addHeader(HttpMessage httpMessage, String s, String s1) { + httpMessage.addHeader(s, s1); + } + + @Override + protected String getTargetServiceName(HttpRequest httpRequest) { + return httpRequest.getRequestLine().getUri(); + } + + @Override + protected String getServiceName(HttpRequest httpRequest) { + return URI.create(httpRequest.getRequestLine().getUri()).getPath(); + } + + @Override + protected int getHttpStatusCode(HttpResponse httpResponse) { + return httpResponse.getStatusLine().getStatusCode(); + } + + @Override + protected String getResponseCode(HttpResponse httpResponse) { + return String.valueOf(httpResponse.getStatusLine().getStatusCode()); + } + + @Override + protected String getTargetEntity(HttpRequest httpRequest) { + //fallback to default value that provided by AbstractMetricLogFilter + return null; + } + + @Override + public void process(HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException { + super.post(null, httpResponse); + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/Logger.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/Logger.java deleted file mode 100644 index 8fbc44c46e..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/Logger.java +++ /dev/null @@ -1,571 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.wrappers; - -import com.google.common.annotations.VisibleForTesting; -import org.openecomp.sdc.common.config.EcompErrorConfiguration; -import org.openecomp.sdc.common.log.elements.LoggerDebug; -import org.openecomp.sdc.common.log.elements.LoggerError; -import org.openecomp.sdc.common.log.elements.LoggerFactory; -import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.slf4j.Marker; - - -/** - * This class wraps {@link org.slf4j.Logger} object and provides mandatory information required by Ecomp logging rules. - * Note: All deprecated methods are supported to be compatible to the legacy code - * and have not be used by the new code - */ -public class Logger implements org.slf4j.Logger { - private final LoggerDebug debug; - private final LoggerError error; - private final org.slf4j.Logger logger; - - @VisibleForTesting - private Logger(org.slf4j.Logger logger) { - this.logger = logger; - this.debug = LoggerFactory.getMdcLogger(LoggerDebug.class, logger); - this.error = LoggerFactory.getMdcLogger(LoggerError.class, logger); - } - - private Logger(String className) { - this(org.slf4j.LoggerFactory.getLogger(className)); - } - - public static Logger getLogger(String className) { - return new Logger(className); - } - - public static Logger getLogger(Class clazz) { - return new Logger(clazz.getName()); - } - - - public boolean isDebugEnabled() { - return logger.isDebugEnabled(); - } - - @Override - public String getName() { - return logger.getName(); - } - - public boolean isTraceEnabled() { - return logger.isTraceEnabled(); - } - - public boolean isErrorEnabled() { - return logger.isErrorEnabled(); - } - - public boolean isWarnEnabled() { - return logger.isWarnEnabled(); - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(String msg) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg); - } - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(String msg, Object o) { - - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg, o); - } - } - - public boolean isInfoEnabled() { - return logger.isInfoEnabled(); - } - - @Override - public void info(String msg) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg); - } - } - - @Override - public void info(String msg, Object o) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg, o); - } - } - - @Override - public void info(String msg, Object o, Object o1) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg, o, o1); - } - } - - public void debug(String msg, Object... params) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg, params); - } - } - - @Override - public void debug(String msg, Throwable throwable) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg, throwable); - } - } - - @Override - public boolean isDebugEnabled(Marker marker) { - return false; - } - - @Override - public void debug(Marker marker, String msg) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg); - } - } - - @Override - public void debug(Marker marker, String msg, Object o) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg, o); - } - } - - @Override - public void debug(Marker marker, String msg, Object o, Object o1) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg, o, o1); - } - } - - @Override - public void debug(Marker marker, String msg, Object... objects) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg, objects); - } - } - - @Override - public void debug(Marker marker, String msg, Throwable throwable) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg, throwable); - } - } - - public void debug(String message) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, message); - } - } - - @Override - public void debug(String msg, Object o) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg, o); - } - } - - @Override - public void debug(String msg, Object o, Object o1) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg, o, o1); - } - } - - public void trace(String message, Object... params) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, message, params); - } - } - - @Override - public void trace(String msg, Throwable throwable) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg, throwable); - } - } - - @Override - public boolean isTraceEnabled(Marker marker) { - return false; - } - - @Override - public void trace(Marker marker, String msg) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg); - } - } - - @Override - public void trace(Marker marker, String msg, Object o) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg, o); - } - } - - @Override - public void trace(Marker marker, String msg, Object o, Object o1) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg, o, o1); - } - } - - @Override - public void trace(Marker marker, String msg, Object... objects) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg, objects); - } - } - - @Override - public void trace(Marker marker, String msg, Throwable throwable) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg, throwable); - } - } - - public void trace(String msg) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg); - } - } - - @Override - public void trace(String msg, Object o) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg, o); - } - } - - @Override - public void trace(String msg, Object o, Object o1) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg, o, o1); - } - } - - public void info(String msg, Object... params) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg, params); - } - } - - @Override - public void info(String msg, Throwable throwable) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg, throwable); - } - } - - @Override - public boolean isInfoEnabled(Marker marker) { - return false; - } - - @Override - public void info(Marker marker, String msg) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg); - } - } - - @Override - public void info(Marker marker, String msg, Object o) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg, o); - } - } - - @Override - public void info(Marker marker, String msg, Object o, Object o1) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg, o, o1); - } - } - - @Override - public void info(Marker marker, String msg, Object... objects) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg, objects); - } - } - - @Override - public void info(Marker marker, String msg, Throwable throwable) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg, throwable); - } - } - - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(String msg, Object... params) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg, params); - } - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(String msg, Object o, Object o1) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg, o, o1); - } - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(String msg, Throwable throwable) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg, throwable); - } - } - - @Override - public boolean isWarnEnabled(Marker marker) { - return false; - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(Marker marker, String msg) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg); - } - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(Marker marker, String msg, Object o) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg, o); - } - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(Marker marker, String msg, Object o, Object o1) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg, o, o1); - } - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(Marker marker, String msg, Object... objects) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg, objects); - } - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(Marker marker, String msg, Throwable throwable) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg, throwable); - } - } - - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(String msg, Object... params) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg, params); - } - } - - @Override - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(String msg, Throwable throwable) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg, throwable); - } - } - - @Override - public boolean isErrorEnabled(Marker marker) { - return false; - } - - @Override - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(Marker marker, String msg) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg); - } - } - - @Override - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(Marker marker, String msg, Object o) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg, o); - } - } - - @Override - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(Marker marker, String msg, Object o, Object o1) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg, o, o1); - } - } - - @Override - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(Marker marker, String msg, Object... params) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg, params); - } - } - - @Override - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(Marker marker, String msg, Throwable throwable) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg, throwable); - } - } - - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(String msg) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg); - } - } - - @Override - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(String msg, Object o) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg, o); - } - } - - @Override - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(String msg, Object o, Object o1) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg, o, o1); - } - } - - /** - * Writes out ERROR logging level message to the application error log - * - * @param errorLevel code representing the error severity level - * @param serviceName name of the API invoked at the logging component - * @param targetEntity name of the ECOMP component or sub-component, or external entity at which the error occurred or null - * @param errorDescription a human readable description of the error condition - * @param params optional parameters of a given error description - */ - public void error(EcompErrorConfiguration.EcompErrorSeverity errorLevel, - EcompLoggerErrorCode errorCodeEnum, - String serviceName, - String targetEntity, - String errorDescription, Object... params) { - if (isErrorEnabled()) { - error.log(errorLevel, errorCodeEnum, serviceName, targetEntity, errorDescription, params); - } - } - - /** - * Writes out ERROR logging level message to the application error log - * - * @param errorCodeEnum code representing the error condition - * @param serviceName name of the API invoked at the logging component - * @param targetEntity name of the ECOMP component or sub-component, or external entity at which the error occurred or null - * @param errorDescription a human readable description of the error condition - * @param params optional parameters of a given error description - */ - public void error(EcompLoggerErrorCode errorCodeEnum, - String serviceName, - String targetEntity, - String errorDescription, Object... params) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, errorCodeEnum, serviceName, targetEntity, errorDescription, params); - } - } - - /** - * Writes out WARN logging level message to the application error log - * - * @param errorCodeEnum code representing the error condition - * @param serviceName name of the API invoked at the logging component - * @param targetEntity name of the ECOMP component or sub-component, or external entity at which the error occurred or null - * @param errorDescription a human readable description of the error condition - * @param params optional parameters of a given error description - */ - public void warn(EcompLoggerErrorCode errorCodeEnum, - String serviceName, - String targetEntity, - String errorDescription, Object... params) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, errorCodeEnum, serviceName, targetEntity, errorDescription, params); - } - } - - /** - * Writes out FATAL logging level message to the application error log - * - * @param errorCodeEnum code representing the error condition - * @param serviceName name of the API invoked at the logging component - * @param targetEntity name of the ECOMP component or sub-component, or external entity at which the error occurred or null - * @param errorDescription a human readable description of the error condition - * @param params optional parameters of a given error description - */ - public void fatal(EcompLoggerErrorCode errorCodeEnum, - String serviceName, - String targetEntity, - String errorDescription, Object... params) { - if (isErrorEnabled()) { - error.log(LogLevel.FATAL, errorCodeEnum, serviceName, targetEntity, errorDescription, params); - } - } - - -} - diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcAudit.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcAudit.java deleted file mode 100644 index aac4e2b1c8..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcAudit.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.wrappers; - -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.log.elements.LoggerAudit; -import org.openecomp.sdc.common.log.elements.LoggerFactory; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.openecomp.sdc.common.log.enums.Severity; -import org.openecomp.sdc.common.util.ThreadLocalsHolder; -import org.slf4j.MDC; - -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.core.Response; - - -/** - * Created by dd4296 on 12/19/2017. - *

    - * audit log for asdc using the log library - * this is adapted for filter classes - */ -public class LoggerSdcAudit extends LoggerSdcUtilBase { - - private static final String AUDIT_ON = "auditOn"; - private String className; - private final LoggerAudit ecompLoggerAudit; - - public LoggerSdcAudit(Class clazz) { - this.className = clazz.getName(); - ecompLoggerAudit = LoggerFactory.getMdcLogger(LoggerAudit.class, org.slf4j.LoggerFactory.getLogger(clazz)); - } - - public void startLog(ContainerRequestContext requestContext) { - ecompLoggerAudit.clear() - .startTimer() - .setPartnerName(getPartnerName( - requestContext.getHeaderString("user-agent"), - requestContext.getHeaderString("USER_ID"), - getUrl(requestContext))) - .setServiceName(getServiceName(requestContext)) - .setKeyRequestId(ThreadLocalsHolder.getUuid()); - MDC.put(AUDIT_ON, "true"); - } - - public static boolean isFlowBeingTakenCare() { - String auditOn = MDC.get(AUDIT_ON); - return !StringUtils.isEmpty(auditOn) && "true".equals(auditOn); - } - - //this function clears the MDC data that relevant for this class - public void clearMyData() { - ecompLoggerAudit.clear(); - } - - public void log(String remoteAddress, - ContainerRequestContext requestContext, - Response.StatusType statusInfo, - LogLevel logLevel, - Severity securityLevel, - String message) { - - try { - - String msg = ecompLoggerAudit.getAuditMessage() == null - ? message : ecompLoggerAudit.getAuditMessage(); - ecompLoggerAudit.stopTimer() - .setRemoteHost(remoteAddress) - .setResponseCode(convertHttpCodeToErrorCode(statusInfo.getStatusCode())) - .setStatusCode(Integer.toString(statusInfo.getStatusCode())) - .setResponseDesc(statusInfo.getReasonPhrase()) - .setInstanceUUID(requestContext.getHeaderString(Constants.X_ECOMP_INSTANCE_ID_HEADER)) - .setOptServiceInstanceId(requestContext.getHeaderString(Constants.X_ECOMP_SERVICE_ID_HEADER)) - .setOptClassName(className) - .setOptAlertSeverity(securityLevel) - .setOptCustomField1(requestContext.getMethod() + ": " + getUrl(requestContext)) - .setOptCustomField2(Integer.toString(statusInfo.getStatusCode())) - .log(logLevel, msg); - } catch (Exception e) { - log.warn("Failed to write to Audit Log. Original Message: {}", message, e); - } finally { - MDC.put(AUDIT_ON, "false"); - } - } -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcUtilBase.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcUtilBase.java deleted file mode 100644 index 86d43235c0..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcUtilBase.java +++ /dev/null @@ -1,221 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.wrappers; - -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ws.rs.container.ContainerRequestContext; -import java.util.List; -import java.util.StringTokenizer; - -import static java.net.HttpURLConnection.HTTP_BAD_METHOD; -import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; -import static java.net.HttpURLConnection.HTTP_CLIENT_TIMEOUT; -import static java.net.HttpURLConnection.HTTP_CONFLICT; -import static java.net.HttpURLConnection.HTTP_ENTITY_TOO_LARGE; -import static java.net.HttpURLConnection.HTTP_FORBIDDEN; -import static java.net.HttpURLConnection.HTTP_GONE; -import static java.net.HttpURLConnection.HTTP_LENGTH_REQUIRED; -import static java.net.HttpURLConnection.HTTP_NOT_ACCEPTABLE; -import static java.net.HttpURLConnection.HTTP_NOT_FOUND; -import static java.net.HttpURLConnection.HTTP_PAYMENT_REQUIRED; -import static java.net.HttpURLConnection.HTTP_PRECON_FAILED; -import static java.net.HttpURLConnection.HTTP_PROXY_AUTH; -import static java.net.HttpURLConnection.HTTP_REQ_TOO_LONG; -import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; -import static java.net.HttpURLConnection.HTTP_UNSUPPORTED_TYPE; - -/** - * Created by dd4296 on 12/20/2017. - *

    - * base class for metric and audit log logging - * holding the specific logic for data extraction - */ -public class LoggerSdcUtilBase { - - private static final int SUCCESS_ERROR_CODE_LIMIT = 399; - private static final int BUSINESS_PROCESS_ERROR_BOUNDRY = 499; - protected static Logger log = LoggerFactory.getLogger(LoggerSdcUtilBase.class.getName()); - - String getRequestIDfromHeaders(List requestHeader) { - // this method gets list of type object. - // toString method returns the RequestId with brackets. - String requestHeaderString = requestHeader.toString(); - return requestHeaderString.replace("[", "").replace("]", ""); - } - - - // this method translates http error code to ECOMP Logger Error code - // this is a naive translation and is not a result of any documented format ECOMP specification - protected EcompLoggerErrorCode convertHttpCodeToErrorCode(int httpResponseCode) { - if (isSuccessError(httpResponseCode)) { - return EcompLoggerErrorCode.SUCCESS; - } - - if (isSchemaError(httpResponseCode)) { - return EcompLoggerErrorCode.SCHEMA_ERROR; - } - if (isDataError(httpResponseCode)) { - return EcompLoggerErrorCode.DATA_ERROR; - } - if (isPermissionsError(httpResponseCode)) { - return EcompLoggerErrorCode.PERMISSION_ERROR; - } - if (isTimeoutOrAvailabilityError(httpResponseCode)) { - return EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR; - } - if (isBusinessProcessError(httpResponseCode)) { - return EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR; - } - return EcompLoggerErrorCode.UNKNOWN_ERROR; - } - - private boolean isTimeoutOrAvailabilityError(int httpResponseCode) { - - switch (httpResponseCode) { - case HTTP_BAD_REQUEST: - case HTTP_UNAUTHORIZED: - case HTTP_NOT_FOUND: - case HTTP_CLIENT_TIMEOUT: - case HTTP_GONE: - return true; - default: - return false; - } - - } - - private boolean isPermissionsError(int httpResponseCode) { - - switch (httpResponseCode) { - case HTTP_PAYMENT_REQUIRED: - case HTTP_FORBIDDEN: - case HTTP_BAD_METHOD: - case HTTP_PROXY_AUTH: - return true; - - default: - return false; - } - } - - private boolean isDataError(int httpResponseCode) { - - switch (httpResponseCode) { - case HTTP_NOT_ACCEPTABLE: - case HTTP_LENGTH_REQUIRED: - case HTTP_PRECON_FAILED: - case HTTP_REQ_TOO_LONG: - case HTTP_ENTITY_TOO_LARGE: - case HTTP_UNSUPPORTED_TYPE: - return true; - - default: - return false; - } - } - - private boolean isSchemaError(int httpResponseCode) { - return HTTP_CONFLICT == httpResponseCode; - } - - private boolean isSuccessError(int httpResponseCode) { - return httpResponseCode < SUCCESS_ERROR_CODE_LIMIT; - } - - private boolean isBusinessProcessError(int httpResponseCode) { - return httpResponseCode > BUSINESS_PROCESS_ERROR_BOUNDRY; - } - - protected String getPartnerName(String userAgent, String userId, String url) { - - if (!StringUtils.isEmpty(userId)) { - return userId; - } - - String urlUser = getUserIdFromUrl(url); - - if (!StringUtils.isEmpty(urlUser)) { - return urlUser; - } - - String userAgentName = getUserIdFromUserAgent(userAgent); - - if (!StringUtils.isEmpty(userAgentName)) { - return userAgentName; - } - - return ""; - } - - private String getUserIdFromUserAgent(String userAgent) { - if (userAgent != null && userAgent.length() > 0) { - if (userAgent.toLowerCase().contains("firefox")) { - return "fireFox_FE"; - } - - if (userAgent.toLowerCase().contains("msie")) { - return "explorer_FE"; - } - - if (userAgent.toLowerCase().contains("chrome")) { - return "chrome_FE"; - } - - return userAgent; - } - return null; - } - - private String getUserIdFromUrl(String url) { - if (url != null && url.toLowerCase().contains("user")) { - StringTokenizer st = new StringTokenizer(url, "/"); - while (st.hasMoreElements()) { - if ("user".equalsIgnoreCase(st.nextToken())) { - return st.nextToken(); - } - } - } - return null; - } - - protected String getUrl(ContainerRequestContext requestContext) { - String url = ""; - - try { - if (requestContext.getUriInfo() != null && requestContext.getUriInfo().getRequestUri() != null) { - url = requestContext.getUriInfo().getRequestUri().toURL().toString(); - } - } catch (Exception ex) { - log.error("failed to get url from request context ", ex); - } - - return url; - } - - protected String getServiceName(ContainerRequestContext requestContext) { - return (requestContext.getUriInfo().getRequestUri().toString()) - .replace(requestContext.getUriInfo().getBaseUri().toString(), "/"); - } -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggingHelper.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggingHelper.java new file mode 100644 index 0000000000..925701eab4 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggingHelper.java @@ -0,0 +1,4 @@ +package org.openecomp.sdc.common.log.wrappers; + +public class LoggingHelper { +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringEvent.java b/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringEvent.java index 257d5a434b..c0cb7829cd 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringEvent.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringEvent.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,105 +20,120 @@ package org.openecomp.sdc.common.monitoring; -import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent; -public class MonitoringEvent extends ESTimeBasedEvent { +import java.util.Formatter; +import java.util.Locale; - private static final String MONITORING_EVENT_TEMPLATE = "hostid=\"%s\" hostcpu=\"%s\" hostmem=\"%s\" hostdisk=\"%s\" " + "jvmid=\"%s\" jvmcpu=\"%s\" jvmmem=\"%s\" jvmtnum=\"%s\" " + "appid=\"%s\" appstat=\"%s\""; +public class MonitoringEvent { - private String hostid; - private Long hostcpu; - private Double hostmem; - private String hostdisk; - private String jvmid; - private Long jvmcpu; - private Long jvmmem; - private Integer jvmtnum; - private String appid; - private String appstat; - - public String getHostid() { - return hostid; - } - - public void setHostid(String hostid) { - this.hostid = hostid; - } - - public Long getHostcpu() { - return hostcpu; - } - - public void setHostcpu(Long hostcpu) { - this.hostcpu = hostcpu; - } - - public Double getHostmem() { - return hostmem; - } - - public void setHostmem(Double hostmem) { - this.hostmem = hostmem; - } - - public String getHostdisk() { - return hostdisk; - } - - public void setHostdisk(String hostdisk) { - this.hostdisk = hostdisk; - } - - public String getJvmid() { - return jvmid; - } - - public void setJvmid(String jvmid) { - this.jvmid = jvmid; - } - - public Long getJvmcpu() { - return jvmcpu; - } - - public void setJvmcpu(Long jvmcpu) { - this.jvmcpu = jvmcpu; - } - - public Long getJvmmem() { - return jvmmem; - } - - public void setJvmmem(Long jvmmem) { - this.jvmmem = jvmmem; - } - - public Integer getJvmtnum() { - return jvmtnum; - } - - public void setJvmtnum(Integer jvmtnum) { - this.jvmtnum = jvmtnum; - } - - public String getAppid() { - return appid; - } - - public void setAppid(String appid) { - this.appid = appid; - } - - public String getAppstat() { - return appstat; - } - - public void setAppstat(String appstat) { - this.appstat = appstat; - } - - @Override - public String toString() { - return getFormattedString(MONITORING_EVENT_TEMPLATE, hostid, hostcpu, hostmem, hostdisk, jvmid, jvmcpu, jvmmem, jvmtnum, appid, appstat); - } + private static String MONITORING_EVENT_TEMPLATE = "hostid=\"%s\" hostcpu=\"%s\" hostmem=\"%s\" hostdisk=\"%s\" " + "jvmid=\"%s\" jvmcpu=\"%s\" jvmmem=\"%s\" jvmtnum=\"%s\" " + "appid=\"%s\" appstat=\"%s\""; + + private String hostid; + private Long hostcpu; + private Double hostmem; + private String hostdisk; + private String jvmid; + private Long jvmcpu; + private Long jvmmem; + private Integer jvmtnum; + private String appid; + private String appstat; + + public String getHostid() { + return hostid; + } + + public void setHostid(String hostid) { + this.hostid = hostid; + } + + public Long getHostcpu() { + return hostcpu; + } + + public void setHostcpu(Long hostcpu) { + this.hostcpu = hostcpu; + } + + public Double getHostmem() { + return hostmem; + } + + public void setHostmem(Double hostmem) { + this.hostmem = hostmem; + } + + public String getHostdisk() { + return hostdisk; + } + + public void setHostdisk(String hostdisk) { + this.hostdisk = hostdisk; + } + + public String getJvmid() { + return jvmid; + } + + public void setJvmid(String jvmid) { + this.jvmid = jvmid; + } + + public Long getJvmcpu() { + return jvmcpu; + } + + public void setJvmcpu(Long jvmcpu) { + this.jvmcpu = jvmcpu; + } + + public Long getJvmmem() { + return jvmmem; + } + + public void setJvmmem(Long jvmmem) { + this.jvmmem = jvmmem; + } + + public Integer getJvmtnum() { + return jvmtnum; + } + + public void setJvmtnum(Integer jvmtnum) { + this.jvmtnum = jvmtnum; + } + + public String getAppid() { + return appid; + } + + public void setAppid(String appid) { + this.appid = appid; + } + + public String getAppstat() { + return appstat; + } + + public void setAppstat(String appstat) { + this.appstat = appstat; + } + + private String getFormattedString(String template, Object... params) { + String res = null; + StringBuilder sb = new StringBuilder(); + Formatter formatter = new Formatter(sb, Locale.US); + try { + formatter.format(template, params); + res = formatter.toString(); + } finally { + formatter.close(); + } + return res; + } + + @Override + public String toString() { + return getFormattedString(MONITORING_EVENT_TEMPLATE, hostid, hostcpu, hostmem, hostdisk, jvmid, jvmcpu, jvmmem, jvmtnum, appid, appstat); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringMetricsFetcher.java b/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringMetricsFetcher.java index b5760bb521..ea92156ce1 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringMetricsFetcher.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringMetricsFetcher.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -37,175 +37,174 @@ import java.util.Map; public class MonitoringMetricsFetcher { - private static final int TO_PERCENT_MULTIPLIER = 100; - private static Logger monitoringLogger = LoggerFactory.getLogger("asdc.fe.monitoring.fetcher"); - - private static volatile MonitoringMetricsFetcher instance; - private static RuntimeMXBean runtimeMXBean; - private static ThreadMXBean threadMXBean; - private static MemoryMXBean memoryMXBean; - private static MBeanServer platformMBeanServer; - private static Sigar sigarSession; - - private static String appName; - private static String jvmName = "Unknown"; - private static final String PROCESS_CPU_TIME_ATTR = "ProcessCpuTime"; - - private static final String FE_JVM_NAME = "jetty-fe"; - private static final String BE_JVM_NAME = "jetty-be"; - - private MonitoringMetricsFetcher() { - } - - public static MonitoringMetricsFetcher getInstance() { - if (instance == null) { - instance = init(); - } - return instance; - } - - public MonitoringEvent getMonitoringMetrics() { - MonitoringEvent monitoringEvent = new MonitoringEvent(); - monitoringEvent.setHostid(getFQDN()); - monitoringEvent.setHostcpu(getHostCpuTime()); - monitoringEvent.setHostmem(getHostUsedMemory()); - monitoringEvent.setHostdisk(getHostUsedDisk().toString()); - - monitoringEvent.setJvmid(jvmName); - - monitoringEvent.setJvmcpu(getJvmCpuTime()); - monitoringEvent.setJvmmem(getJvmUsedHeapMemory()); - monitoringEvent.setJvmtnum(getJvmThreads()); - - monitoringEvent.setAppid(appName); - // this is probably from healthcheck - monitoringEvent.setAppstat("appStatus"); - return monitoringEvent; - } - - private static synchronized MonitoringMetricsFetcher init() { - if (instance == null) { - instance = new MonitoringMetricsFetcher(); - threadMXBean = ManagementFactory.getThreadMXBean(); - memoryMXBean = ManagementFactory.getMemoryMXBean(); - runtimeMXBean = ManagementFactory.getRuntimeMXBean(); - platformMBeanServer = ManagementFactory.getPlatformMBeanServer(); - sigarSession = new Sigar(); - appName = ExternalConfiguration.getAppName(); - monitoringLogger.debug("appName is {}", appName); - // Accoridng to Yaki, there is no "calculated" jvmName like it was - // in TAS, - // just "jetty-be" or "jetty-fe" - if (appName.contains("fe")) { - jvmName = FE_JVM_NAME; - } else if (appName.contains("be")) { - jvmName = BE_JVM_NAME; - } else { - monitoringLogger - .warn("Couldn't determine jvmName, appName is expected to contain \"be\" or \"fe\" string"); - } - } - return instance; - } - - /** - * Returns the number of live threads for this JVM - * - * @return number of live threads - */ - private Integer getJvmThreads() { - return threadMXBean.getThreadCount(); - } - - /** - * Returns the number of used heap memory (bytes) - * - * @return the number of used heap memory (bytes) - */ - private long getJvmUsedHeapMemory() { - return memoryMXBean.getHeapMemoryUsage().getUsed(); - } - - /** - * Returns the jvm cpu time (msec) - * - * @return the jvm cpu time (msec) - */ - private long getJvmCpuTime() { - - long cpuTime = -1; - try { - cpuTime = (long) platformMBeanServer.getAttribute( - new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME), PROCESS_CPU_TIME_ATTR); - } catch (Exception e) { - monitoringLogger.error("Couldn't measure JVM CPU time, error: {}", e); - } - return cpuTime; - } - - /** - * Returns the host total cpu time (msec) - * - * @return the host total cpu time (msec) - */ - private long getHostCpuTime() { - long cpuTime = -1; - try { - cpuTime = sigarSession.getCpu().getTotal(); - } catch (Exception e) { - monitoringLogger.error("Couldn't measure host CPU time, error: {}", e); - } - return cpuTime; - } - - /** - * Returns the host used memory(msec) - * - * @return the host used memory(msec) - */ - private Double getHostUsedMemory() { - Double memory = -1.0; - try { - memory = sigarSession.getMem().getUsedPercent(); - } catch (Exception e) { - monitoringLogger.error("Couldn't measure host used memory, error: {}", e); - } - return memory; - } - - /** - * Returns the percentage of all available FS - * - * @return the host avail disk(bytes) - */ - private Map getHostUsedDisk() { - Map res = new HashMap<>(); - try { - FileSystem[] fileSystemList = sigarSession.getFileSystemList(); - for (FileSystem fileSystem : fileSystemList) { - - String dirName = fileSystem.getDirName(); - double usePercent = sigarSession.getFileSystemUsage(dirName).getUsePercent() * TO_PERCENT_MULTIPLIER; - res.put(dirName, usePercent); - } - } catch (Exception e) { - monitoringLogger.error("Couldn't measure host used disk, error: {}", e); - } - return res; - } - - /** - * Returns the FQDN - * - * @return the FQDN - */ - private String getFQDN() { - String fqdn = ""; - try { - fqdn = sigarSession.getFQDN(); - } catch (Exception e) { - monitoringLogger.error("Couldn't get FQDN, error: {}", e); - } - return fqdn; - } + private static Logger monitoringLogger = LoggerFactory.getLogger("asdc.fe.monitoring.fetcher"); + + private static volatile MonitoringMetricsFetcher instance; + private static RuntimeMXBean runtimeMXBean; + private static ThreadMXBean threadMXBean; + private static MemoryMXBean memoryMXBean; + private static MBeanServer platformMBeanServer; + private static Sigar sigarSession; + + private static String appName; + private static String jvmName = "Unknown"; + private final String PROCESS_CPU_TIME_ATTR = "ProcessCpuTime"; + + private static String FE_JVM_NAME = "jetty-fe"; + private static String BE_JVM_NAME = "jetty-be"; + + private MonitoringMetricsFetcher() { + }; + + public static MonitoringMetricsFetcher getInstance() { + if (instance == null) { + instance = init(); + } + return instance; + } + + public MonitoringEvent getMonitoringMetrics() { + MonitoringEvent monitoringEvent = new MonitoringEvent(); + monitoringEvent.setHostid(getFQDN()); + monitoringEvent.setHostcpu(getHostCpuTime()); + monitoringEvent.setHostmem(getHostUsedMemory()); + monitoringEvent.setHostdisk(getHostUsedDisk().toString()); + + monitoringEvent.setJvmid(jvmName); + + monitoringEvent.setJvmcpu(getJvmCpuTime()); + monitoringEvent.setJvmmem(getJvmUsedHeapMemory()); + monitoringEvent.setJvmtnum(getJvmThreads()); + + monitoringEvent.setAppid(appName); + // this is probably from healthcheck + monitoringEvent.setAppstat("appStatus"); + return monitoringEvent; + } + + private static synchronized MonitoringMetricsFetcher init() { + if (instance == null) { + instance = new MonitoringMetricsFetcher(); + threadMXBean = ManagementFactory.getThreadMXBean(); + memoryMXBean = ManagementFactory.getMemoryMXBean(); + runtimeMXBean = ManagementFactory.getRuntimeMXBean(); + platformMBeanServer = ManagementFactory.getPlatformMBeanServer(); + sigarSession = new Sigar(); + appName = ExternalConfiguration.getAppName(); + monitoringLogger.debug("appName is {}", appName); + // Accoridng to Yaki, there is no "calculated" jvmName like it was + // in TAS, + // just "jetty-be" or "jetty-fe" + if (appName.contains("fe")) { + jvmName = FE_JVM_NAME; + } else if (appName.contains("be")) { + jvmName = BE_JVM_NAME; + } else { + monitoringLogger + .warn("Couldn't determine jvmName, appName is expected to contain \"be\" or \"fe\" string"); + } + } + return instance; + } + + /** + * Returns the number of live threads for this JVM + * + * @return number of live threads + */ + private Integer getJvmThreads() { + return threadMXBean.getThreadCount(); + } + + /** + * Returns the number of used heap memory (bytes) + * + * @return the number of used heap memory (bytes) + */ + private long getJvmUsedHeapMemory() { + return memoryMXBean.getHeapMemoryUsage().getUsed(); + } + + /** + * Returns the jvm cpu time (msec) + * + * @return the jvm cpu time (msec) + */ + private long getJvmCpuTime() { + + long cpuTime = -1; + try { + cpuTime = (long) platformMBeanServer.getAttribute( + new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME), PROCESS_CPU_TIME_ATTR); + } catch (Exception e) { + monitoringLogger.error("Couldn't measure JVM CPU time, error: {}", e); + } + return cpuTime; + } + + /** + * Returns the host total cpu time (msec) + * + * @return the host total cpu time (msec) + */ + private long getHostCpuTime() { + long cpuTime = -1; + try { + cpuTime = sigarSession.getCpu().getTotal(); + } catch (Exception e) { + monitoringLogger.error("Couldn't measure host CPU time, error: {}", e); + } + return cpuTime; + } + + /** + * Returns the host used memory(msec) + * + * @return the host used memory(msec) + */ + private Double getHostUsedMemory() { + Double memory = -1.0; + try { + memory = sigarSession.getMem().getUsedPercent(); + } catch (Exception e) { + monitoringLogger.error("Couldn't measure host used memory, error: {}", e); + } + return memory; + } + + /** + * Returns the percentage of all available FS + * + * @return the host avail disk(bytes) + */ + private Map getHostUsedDisk() { + Map res = new HashMap<>(); + try { + FileSystem[] fileSystemList = sigarSession.getFileSystemList(); + for (FileSystem fileSystem : fileSystemList) { + + String dirName = fileSystem.getDirName(); + double usePercent = sigarSession.getFileSystemUsage(dirName).getUsePercent() * 100; + res.put(dirName, usePercent); + } + } catch (Exception e) { + monitoringLogger.error("Couldn't measure host used disk, error: {}", e); + } + return res; + } + + /** + * Returns the FQDN + * + * @return the FQDN + */ + private String getFQDN() { + String fqdn = ""; + try { + fqdn = sigarSession.getFQDN(); + } catch (Exception e) { + monitoringLogger.error("Couldn't get FQDN, error: {}", e); + } + return fqdn; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestConfigurationInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestConfigurationInfo.java index 0e660400d3..89a9e24dff 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestConfigurationInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestConfigurationInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,80 +24,84 @@ import org.openecomp.sdc.common.api.BasicConfiguration; public class RestConfigurationInfo extends BasicConfiguration { - private Integer readTimeoutInSec = null; - - private Boolean ignoreCertificate = null; - - private Integer connectionPoolSize = null; - - private Integer connectTimeoutInSec = null; - - /** - * @return the readTimeoutInSec - */ - public Integer getReadTimeoutInSec() { - return readTimeoutInSec; - } - - /** - * @param readTimeoutInSec the readTimeoutInSec to set - */ - public void setReadTimeoutInSec(Integer readTimeoutInSec) { - this.readTimeoutInSec = readTimeoutInSec; - } - - /** - * @return the ignoreCertificate - */ - public Boolean getIgnoreCertificate() { - return ignoreCertificate; - } - - /** - * @param ignoreCertificate the ignoreCertificate to set - */ - public void setIgnoreCertificate(Boolean ignoreCertificate) { - this.ignoreCertificate = ignoreCertificate; - } - - /** - * @return the connectionPoolSize - */ - public Integer getConnectionPoolSize() { - return connectionPoolSize; - } - - /** - * @param connectionPoolSize the connectionPoolSize to set - */ - public void setConnectionPoolSize(Integer connectionPoolSize) { - this.connectionPoolSize = connectionPoolSize; - } - - /** - * @return the connectTimeoutInSec - */ - public Integer getConnectTimeoutInSec() { - return connectTimeoutInSec; - } - - /** - * @param connectTimeoutInSec the connectTimeoutInSec to set - */ - public void setConnectTimeoutInSec(Integer connectTimeoutInSec) { - this.connectTimeoutInSec = connectTimeoutInSec; - } - - public String toString() { - - StringBuilder builder = new StringBuilder(); - - builder.append("[ timeoutInSec=" + readTimeoutInSec + ","); - builder.append("connectTimeoutInSec=" + connectTimeoutInSec + ","); - builder.append("ignoreCertificate=" + ignoreCertificate + ","); - builder.append("connectionPoolSize=" + connectionPoolSize + "]"); - - return builder.toString(); - - } + private Integer readTimeoutInSec = null; + + private Boolean ignoreCertificate = null; + + private Integer connectionPoolSize = null; + + private Integer connectTimeoutInSec = null; + + /** + * @return the readTimeoutInSec + */ + public Integer getReadTimeoutInSec() { + return readTimeoutInSec; + } + + /** + * @param readTimeoutInSec + * the readTimeoutInSec to set + */ + public void setReadTimeoutInSec(Integer readTimeoutInSec) { + this.readTimeoutInSec = readTimeoutInSec; + } + + /** + * @return the ignoreCertificate + */ + public Boolean getIgnoreCertificate() { + return ignoreCertificate; + } + + /** + * @param ignoreCertificate + * the ignoreCertificate to set + */ + public void setIgnoreCertificate(Boolean ignoreCertificate) { + this.ignoreCertificate = ignoreCertificate; + } + + /** + * @return the connectionPoolSize + */ + public Integer getConnectionPoolSize() { + return connectionPoolSize; + } + + /** + * @param connectionPoolSize + * the connectionPoolSize to set + */ + public void setConnectionPoolSize(Integer connectionPoolSize) { + this.connectionPoolSize = connectionPoolSize; + } + + /** + * @return the connectTimeoutInSec + */ + public Integer getConnectTimeoutInSec() { + return connectTimeoutInSec; + } + + /** + * @param connectTimeoutInSec + * the connectTimeoutInSec to set + */ + public void setConnectTimeoutInSec(Integer connectTimeoutInSec) { + this.connectTimeoutInSec = connectTimeoutInSec; + } + + public String toString() { + + StringBuilder builder = new StringBuilder(); + + builder.append("[ timeoutInSec=" + readTimeoutInSec + ","); + builder.append("connectTimeoutInSec=" + connectTimeoutInSec + ","); + builder.append("ignoreCertificate=" + ignoreCertificate + ","); + builder.append("connectionPoolSize=" + connectionPoolSize + "]"); + + return builder.toString(); + + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RequestHeadersValidator.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RequestHeadersValidator.java index 5c389fcd3f..6703b91a60 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RequestHeadersValidator.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RequestHeadersValidator.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,64 +31,64 @@ import java.util.List; import java.util.Map; public class RequestHeadersValidator { - private static Logger log = Logger.getLogger(RequestHeadersValidator.class.getName()); + private static Logger log = Logger.getLogger(RequestHeadersValidator.class.getName()); - public static void validateContentType(HttpServletRequest request, MediaType expectedContentType, - Map headersMap) throws RestRequestValidationException { + public static void validateContentType(HttpServletRequest request, MediaType expectedContentType, + Map headersMap) throws RestRequestValidationException { - log.debug("validateContentType - expected: {}", expectedContentType); - if (request == null || expectedContentType == null) { - throw new RestRequestValidationException("request or media-type are null"); - } - String contentType = request.getHeader(Constants.CONTENT_TYPE_HEADER); - if (contentType == null || !contentType.contains(MediaType.APPLICATION_JSON)) { - throw new RestRequestValidationException( - "Content-Type of requset is different then " + expectedContentType); - } else { - headersMap.put(Constants.CONTENT_TYPE_HEADER, contentType); - } - } + log.debug("validateContentType - expected: {}", expectedContentType); + if (request == null || expectedContentType == null) { + throw new RestRequestValidationException("request or media-type are null"); + } + String contentType = request.getHeader(Constants.CONTENT_TYPE_HEADER); + if (contentType == null || !contentType.contains(MediaType.APPLICATION_JSON)) { + throw new RestRequestValidationException( + "Content-Type of requset is different then " + expectedContentType); + } else { + headersMap.put(Constants.CONTENT_TYPE_HEADER, contentType); + } + } - public static void validateIdentificationHeaders(HttpServletRequest request, List identificationList, - Map headersMap) throws RestRequestValidationException { + public static void validateIdentificationHeaders(HttpServletRequest request, List identificationList, + Map headersMap) throws RestRequestValidationException { - log.debug("validateIdentificationHeaders"); - for (String requiredHeader : identificationList) { - String headerVal = request.getHeader(requiredHeader); - if (headerVal != null && !headerVal.isEmpty()) { - headersMap.put(requiredHeader, headerVal); - log.debug("found header - {} : {}", requiredHeader, headerVal); - } else { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "missing identification header: {}", requiredHeader); - throw new RestRequestValidationException("missing identification header: " + requiredHeader); - } - } + log.debug("validateIdentificationHeaders"); + for (String requiredHeader : identificationList) { + String headerVal = request.getHeader(requiredHeader); + if (headerVal != null && !headerVal.isEmpty()) { + headersMap.put(requiredHeader, headerVal); + log.debug("found header - {} : {}", requiredHeader, headerVal); + } else { + log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","missing identification header: {}", requiredHeader); + throw new RestRequestValidationException("missing identification header: " + requiredHeader); + } + } - } + } - public static void validateMd5(byte[] encodedData, HttpServletRequest request, Map headersMap) - throws RestRequestValidationException { + public static void validateMd5(byte[] encodedData, HttpServletRequest request, Map headersMap) + throws RestRequestValidationException { - // validate parameters - if (encodedData == null || request == null) { - throw new RestRequestValidationException("encoded data or request are not valid"); - } + // validate parameters + if (encodedData == null || request == null) { + throw new RestRequestValidationException("encoded data or request are not valid"); + } - // calculate MD5 on the data - String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(encodedData); - byte[] encodedMd5 = Base64.encodeBase64(md5.getBytes()); + // calculate MD5 on the data + String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(encodedData); + byte[] encodedMd5 = Base64.encodeBase64(md5.getBytes()); - // read the Content-MD5 header - String origMd5 = request.getHeader(Constants.MD5_HEADER); - if ((origMd5 == null) || origMd5.isEmpty()) { - throw new RestRequestValidationException("missing Content-MD5 header "); - } + // read the Content-MD5 header + String origMd5 = request.getHeader(Constants.MD5_HEADER); + if ((origMd5 == null) || origMd5.isEmpty()) { + throw new RestRequestValidationException("missing Content-MD5 header "); + } - // verify MD5 value - if (!origMd5.equals(new String(encodedMd5))) { - throw new RestRequestValidationException("uploaded file failed MD5 validation"); - } - headersMap.put(Constants.MD5_HEADER, origMd5); - } + // verify MD5 value + if (!origMd5.equals(new String(encodedMd5))) { + throw new RestRequestValidationException("uploaded file failed MD5 validation"); + } + headersMap.put(Constants.MD5_HEADER, origMd5); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RestRequestValidationException.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RestRequestValidationException.java index 0dd186a155..90ed39e1c2 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RestRequestValidationException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RestRequestValidationException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,13 +22,13 @@ package org.openecomp.sdc.common.rest.impl.validator; public class RestRequestValidationException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1962654783383591672L; + /** + * + */ + private static final long serialVersionUID = 1962654783383591672L; - public RestRequestValidationException(String message) { - super(message); - } + public RestRequestValidationException(String message) { + super(message); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/servlets/BasicServlet.java b/common-app-api/src/main/java/org/openecomp/sdc/common/servlets/BasicServlet.java index 7f428f253b..9fbf4ca416 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/servlets/BasicServlet.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/servlets/BasicServlet.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java b/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java index 8e50c97623..9faaaf9931 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,24 +28,23 @@ import org.openecomp.sdc.common.impl.FSConfigurationSource; import java.io.File; public class BaseConfDependent { - - protected static ConfigurationManager configurationManager; - protected static String componentName; - protected static String confPath; - - - protected static void setUp() { - ExternalConfiguration.setAppName(componentName); - ExternalConfiguration.setConfigDir(confPath); - ExternalConfiguration.listenForChanges(); - ExternalConfiguration.setAppVersion("1806.666"); - - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); - - configurationManager = new ConfigurationManager(configurationSource); - - configurationManager.getConfiguration().setJanusGraphInMemoryGraph(true); - - } - + protected static ConfigurationManager configurationManager; + protected static String componentName; + protected static String confPath; + + + protected static void setUp(){ + ExternalConfiguration.setAppName(componentName); + ExternalConfiguration.setConfigDir(confPath); + ExternalConfiguration.listenForChanges(); + ExternalConfiguration.setAppVersion("1806.666"); + + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + + configurationManager = new ConfigurationManager(configurationSource); + + configurationManager.getConfiguration().setJanusGraphInMemoryGraph(true); + + } + } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/CapabilityTypeNameEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/CapabilityTypeNameEnum.java index a79e1ee22b..cb78b8ed9b 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/CapabilityTypeNameEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/CapabilityTypeNameEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,26 +21,26 @@ package org.openecomp.sdc.common.util; public enum CapabilityTypeNameEnum { - ROOT("tosca.capabilities.Root"), - NODE("tosca.capabilities.Node"), - CONTAINER("tosca.capabilities.Container"), - ENDPOINT("tosca.capabilities.Endpoint"), - ENDPOINT_PUBLIC("tosca.capabilities.Endpoint.Public"), - ENDPOINT_ADMIN("tosca.capabilities.Endpoint.Admin"), - ENDPOINT_DATABASE("tosca.capabilities.Endpoint.Database"), - OPERATING_SYSTEM("tosca.capabilities.OperatingSystem"), - SCALABLE("tosca.capabilities.Scalable"), - BINDABLE("tosca.capabilities.network.Bindable"), - DOCKER("tosca.capabilities.Container.Docker"), - ATTACHMENT("tosca.capabilities.Attachment"); + ROOT("tosca.capabilities.Root"), + NODE("tosca.capabilities.Node"), + CONTAINER("tosca.capabilities.Container"), + ENDPOINT("tosca.capabilities.Endpoint"), + ENDPOINT_PUBLIC("tosca.capabilities.Endpoint.Public"), + ENDPOINT_ADMIN("tosca.capabilities.Endpoint.Admin"), + ENDPOINT_DATABASE("tosca.capabilities.Endpoint.Database"), + OPERATING_SYSTEM("tosca.capabilities.OperatingSystem"), + SCALABLE("tosca.capabilities.Scalable"), + BINDABLE("tosca.capabilities.network.Bindable"), + DOCKER("tosca.capabilities.Container.Docker"), + ATTACHMENT("tosca.capabilities.Attachment"); - private String capabilityName; + private String capabilityName; - CapabilityTypeNameEnum(String capName) { - this.capabilityName = capName; - } + private CapabilityTypeNameEnum(String capName) { + this.capabilityName = capName; + } - public String getCapabilityName() { - return capabilityName; - } + public String getCapabilityName() { + return capabilityName; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java index 7ff19ace72..d82538a355 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,145 +22,194 @@ package org.openecomp.sdc.common.util; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.log.api.ILogConfiguration; +import org.slf4j.MDC; import java.io.File; import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.regex.Pattern; public class GeneralUtility { - private static final int STRING_LENGTH_MULTIPLIER = 4; - - public static boolean generateTextFile(String fileName, String fileData) { - boolean isSuccessfull = true; - try { - FileUtils.writeStringToFile(new File(fileName), fileData); - } catch (IOException e) { - isSuccessfull = false; - } - return isSuccessfull; + public static boolean generateTextFile(String fileName, String fileData) { + boolean isSuccessfull = true; + try { + FileUtils.writeStringToFile(new File(fileName), fileData); + } catch (IOException e) { + isSuccessfull = false; + } + return isSuccessfull; + } + + /** + * Use with care, usage is not advised!!! + * The method only checks if String does not contain special characters + length divided by 4 with no remainder. + * The methods contained in other common libraries do the same. + */ + public static boolean isBase64Encoded(byte[] data) { + return Base64.isBase64(data); + } + + /** + *Use with care, usage is not advised!!! + * The method only checks if String does not contain special characters + length divided by 4 with no remainder. + * The methods contained in other common libraries do the same. + */ + public static boolean isBase64Encoded(String str) { + boolean isEncoded = false; + try { + // checks if the string was properly padded to the + isEncoded = ((str.length() % 4 == 0) && (Pattern.matches("\\A[a-zA-Z0-9/+]+={0,2}\\z", str))); + if (isEncoded) { + // If no exception is caught, then it is possibly a base64 + // encoded string + byte[] data = Base64.decodeBase64(str); + } + + } catch (Exception e) { + // If exception is caught, then it is not a base64 encoded string + isEncoded = false; + } + return isEncoded; + } + + /** + * Checks whether the passed string exceeds a limit of number of characters. + * + * @param str + * @param limit + * @return the result of comparison, or false if str is null. + */ + public static boolean isExceedingLimit(String str, int limit) { + if (str == null) { + return false; + } + return str.length() > limit; + } + + /** + * Checks the passed string list whether the cumulative length of strings and delimiters between them exceeds a limit of number of characters. For example for list ("one","two","three") with delimiter "," the length of list is calculated + * 3+1+3+1+5=13 + * + * @param strList + * @param limit + * @param delimiterLength + * - 0 if there is no delimeter. + * @return the result of comparison, or false if strList is null. + */ + public static boolean isExceedingLimit(List strList, int limit, int delimiterLength) { + if (strList == null || strList.isEmpty()) { + return false; + } + int sum = 0; + int size = strList.size(); + for (int i = 0; i < size - 1; i++) { + String str = strList.get(i); + if (str != null) { + sum += str.length(); + } + sum += delimiterLength; + } + String str = strList.get(size - 1); + if (str != null) { + sum += str.length(); + } + return sum > limit; + } + + /** + * Return the extension as the substring from the last dot. For input "kuku.txt", "txt" will be returned. If no dot is found or input is null, empty string is returned. + * + * @param fileName + * @return extension + */ + public static String getFilenameExtension(String fileName) { + String res = Constants.EMPTY_STRING; + if (fileName != null) { + int indexOf = fileName.lastIndexOf('.'); + if (indexOf != -1 && indexOf < (fileName.length() - 1)) { + res = fileName.substring(indexOf + 1); + } + } + return res; + } + + public static String calculateMD5Base64EncodedByByteArray(byte[] payload) { + String decodedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(payload); + byte[] encodeMd5 = Base64.encodeBase64(decodedMd5.getBytes()); + return new String(encodeMd5); + + } + + /** + * + * @param data + * @return + */ + public static String calculateMD5Base64EncodedByString(String data) { + String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data); + + // encode base-64 result + byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes()); + return new String(encodeBase64); + } + + + /** + * + * @param String + * @return String is null or Empty + */ + public static boolean isEmptyString(String str) { + return str == null || str.trim().isEmpty(); } - /** - * Use with care, usage is not advised!!! - * The method only checks if String does not contain special characters + length divided by 4 with no remainder. - * The methods contained in other common libraries do the same. - */ - public static boolean isBase64Encoded(byte[] data) { - return Base64.isBase64(data); - } + public static String getEcompRequestId() { + return MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); + } - /** - * Use with care, usage is not advised!!! - * The method only checks if String does not contain special characters + length divided by 4 with no remainder. - * The methods contained in other common libraries do the same. - */ - public static boolean isBase64Encoded(String str) { - boolean isEncoded = false; - try { - // checks if the string was properly padded to the - isEncoded = ((str.length() % STRING_LENGTH_MULTIPLIER == 0) && (Pattern.matches("\\A[a-zA-Z0-9/+]+={0,2}\\z", str))); - if (isEncoded) { - // If no exception is caught, then it is possibly a base64 - // encoded string - byte[] data = Base64.decodeBase64(str); - } - - } catch (Exception e) { - // If exception is caught, then it is not a base64 encoded string - isEncoded = false; - } - return isEncoded; - } - /** - * Checks whether the passed string exceeds a limit of number of characters. - * - * @param str - * @param limit - * @return the result of comparison, or false if str is null. - */ - public static boolean isExceedingLimit(String str, int limit) { - if (str == null) { - return false; - } - return str.length() > limit; - } - /** - * Checks the passed string list whether the cumulative length of strings and delimiters between them exceeds a limit of number of characters. For example for list ("one","two","three") with delimiter "," the length of list is calculated - * 3+1+3+1+5=13 - * - * @param strList - * @param limit - * @param delimiterLength - 0 if there is no delimeter. - * @return the result of comparison, or false if strList is null. - */ - public static boolean isExceedingLimit(List strList, int limit, int delimiterLength) { - if (strList == null || strList.isEmpty()) { - return false; - } - int sum = 0; - int size = strList.size(); - for (int i = 0; i < size - 1; i++) { - String str = strList.get(i); - if (str != null) { - sum += str.length(); - } - sum += delimiterLength; - } - String str = strList.get(size - 1); - if (str != null) { - sum += str.length(); - } - return sum > limit; - } - /** - * Return the extension as the substring from the last dot. For input "kuku.txt", "txt" will be returned. If no dot is found or input is null, empty string is returned. - * - * @param fileName - * @return extension - */ - public static String getFilenameExtension(String fileName) { - String res = Constants.EMPTY_STRING; - if (fileName != null) { - int indexOf = fileName.lastIndexOf('.'); - if (indexOf != -1 && indexOf < (fileName.length() - 1)) { - res = fileName.substring(indexOf + 1); - } - } - return res; - } + public static Map>> getCategorizedComponents(List components) { - public static String calculateMD5Base64EncodedByByteArray(byte[] payload) { - String decodedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(payload); - byte[] encodeMd5 = Base64.encodeBase64(decodedMd5.getBytes()); - return new String(encodeMd5); + Map>> categorizedMap = new HashMap<>(); + components.forEach(component -> categorizeComponent(component, categorizedMap)); + return categorizedMap; + } - } + private static void categorizeComponent(T component, Map>> categorizedMap) { + if(component.getComponentTypeAsString().equals("SERVICE")){ + categorizeService(component, categorizedMap); + }else if(component.getComponentTypeAsString().equals("RESOURCE")){ + categorizeResource(component, categorizedMap); + } + } - /** - * @param data - * @return - */ - public static String calculateMD5Base64EncodedByString(String data) { - String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data); + private static void categorizeResource(T component, Map>> categorizedMap) { + String category = component.getCategoryName(); + String subCategory = component.getSubcategoryName(); + putComponentToMap(component, categorizedMap, category, subCategory); + } - // encode base-64 result - byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes()); - return new String(encodeBase64); - } + private static void categorizeService(T component, Map>> categorizedMap) { + String category = "Generic"; + String subCategory = "Generic"; + putComponentToMap(component, categorizedMap, category, subCategory); + } + private static void putComponentToMap(T component, Map>> categorizedMap, + String category, String subCategory) { - /** - * @param String - * @return String is null or Empty - */ - public static boolean isEmptyString(String str) { - return str == null || str.trim().isEmpty(); - } + Map> categoryMap = categorizedMap.computeIfAbsent(category, k -> new HashMap<>()); + List subCategoryList = categoryMap.computeIfAbsent(subCategory, k -> new ArrayList<>()); + subCategoryList.add(component); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/GsonFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/GsonFactory.java index e7877e4fad..7c3bcb6cad 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/GsonFactory.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/GsonFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,17 +24,17 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonFactory { - private static Gson gson = null; + private static Gson gson = null; - public static Gson getGson() { - if (gson == null) { - synchronized (GsonFactory.class) { - if (gson == null) { - gson = new GsonBuilder().disableHtmlEscaping().serializeNulls().create(); - } - } - } + public static Gson getGson() { + if (gson == null) { + synchronized (GsonFactory.class) { + if (gson == null) { + gson = new GsonBuilder().disableHtmlEscaping().serializeNulls().create(); + } + } + } - return gson; - } + return gson; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java index 7474d38372..00a03de7cf 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -33,7 +33,6 @@ import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOW public class HealthCheckUtil { private static Logger log = Logger.getLogger(HealthCheckUtil.class.getName()); - public boolean getAggregateStatus(List healthCheckInfos, Collection excludes) { boolean status = true; excludes = CollectionUtils.isEmpty(excludes) ? new ArrayList<>() : excludes; @@ -48,7 +47,7 @@ public class HealthCheckUtil { return status; } - public String getAggregateDescription(List healthCheckInfos, String parentDescription) { + public String getAggregateDescription(List healthCheckInfos) { StringBuilder sb = new StringBuilder(); healthCheckInfos.forEach(x -> { diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HtmlCleaner.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HtmlCleaner.java index 5a7c426949..c9086fc272 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HtmlCleaner.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HtmlCleaner.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,81 +31,81 @@ import java.util.regex.Pattern; public class HtmlCleaner { - private static Set htmlTags = new HashSet<>(); + private static Set htmlTags = new HashSet<>(); - private static String patternHtmlFullTagStr = "\\s]+))?)+\\s*|\\s*)/?>"; + private static String patternHtmlFullTagStr = "\\s]+))?)+\\s*|\\s*)/?>"; - private static String patternHtmlTagOnlyStr = "]*/?>"; + private static String patternHtmlTagOnlyStr = "]*/?>"; - private static Pattern onlyTagPattern = Pattern.compile(patternHtmlTagOnlyStr); + private static Pattern onlyTagPattern = Pattern.compile(patternHtmlTagOnlyStr); - private static Pattern fullTagPattern = Pattern.compile(patternHtmlFullTagStr); + private static Pattern fullTagPattern = Pattern.compile(patternHtmlFullTagStr); - static { - Tag[] allTags = HTML.getAllTags(); - for (Tag tag : allTags) { - htmlTags.add(tag.toString().toLowerCase()); - } - } + static { + Tag[] allTags = HTML.getAllTags(); + for (Tag tag : allTags) { + htmlTags.add(tag.toString().toLowerCase()); + } + } - public static String stripHtml(String input) { + public static String stripHtml(String input) { - return stripHtml(input, false); + return stripHtml(input, false); - } + } - public static String stripHtml(String input, boolean toEscape) { + public static String stripHtml(String input, boolean toEscape) { - if (input == null || input.isEmpty()) { - return input; - } + if (input == null || input.isEmpty()) { + return input; + } - Matcher matcher = onlyTagPattern.matcher(input); + Matcher matcher = onlyTagPattern.matcher(input); - Set tagsToRemove = new HashSet<>(); + Set tagsToRemove = new HashSet<>(); - while (matcher.find()) { + while (matcher.find()) { - int start = matcher.start(); - int end = matcher.end(); + int start = matcher.start(); + int end = matcher.end(); - String matchTag = input.substring(start, end); + String matchTag = input.substring(start, end); - int groupCount = matcher.groupCount(); + int groupCount = matcher.groupCount(); - if (groupCount > 0) { - String tag = matcher.group(1); - if (tag != null && htmlTags.contains(tag.toLowerCase())) { - if (!tagsToRemove.contains(matchTag)) { - tagsToRemove.add(matchTag); - } - } - } - } + if (groupCount > 0) { + String tag = matcher.group(1); + if (tag != null && htmlTags.contains(tag.toLowerCase())) { + if (!tagsToRemove.contains(matchTag)) { + tagsToRemove.add(matchTag); + } + } + } + } - String stripHtmlStr = removeTagsFromString(tagsToRemove, input); + String stripHtmlStr = removeTagsFromString(tagsToRemove, input); - if (stripHtmlStr != null) { - if (toEscape) { - stripHtmlStr = StringEscapeUtils.escapeHtml4(stripHtmlStr); - } - } + if (stripHtmlStr != null) { + if (toEscape) { + stripHtmlStr = StringEscapeUtils.escapeHtml4(stripHtmlStr); + } + } - return stripHtmlStr; + return stripHtmlStr; - } + } - private static String removeTagsFromString(Set tagsToRemove, String input) { + private static String removeTagsFromString(Set tagsToRemove, String input) { - String stripStr = input; - if (input == null || tagsToRemove.isEmpty()) { - return input; - } + String stripStr = input; + if (input == null || tagsToRemove.isEmpty()) { + return input; + } - for (String tag : tagsToRemove) { - stripStr = stripStr.replaceAll(tag, ""); - } - return stripStr; - } + for (String tag : tagsToRemove) { + stripStr = stripStr.replaceAll(tag, ""); + } + return stripStr; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HttpUtil.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HttpUtil.java index 5bd3b87fc4..d9f099876a 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HttpUtil.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HttpUtil.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -30,50 +30,50 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; public class HttpUtil { - public static Either readJsonStringFromRequest(HttpServletRequest request) { - Either eitherResult; - try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { - ServletInputStream reader = request.getInputStream(); - int value; - while ((value = reader.read()) != -1) { - stream.write(value); - } - eitherResult = Either.left(new String(stream.toByteArray())); - } catch (IOException e) { - eitherResult = Either.right(e); - } - return eitherResult; + public static Either readJsonStringFromRequest(HttpServletRequest request) { + Either eitherResult; + try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { + ServletInputStream reader = request.getInputStream(); + int value; + while ((value = reader.read()) != -1) { + stream.write(value); + } + eitherResult = Either.left(new String(stream.toByteArray())); + } catch (IOException e) { + eitherResult = Either.right(e); + } + return eitherResult; - } + } - /** - * Builds an object from a JSON in the POST Body of the request. - */ - public static Either getObjectFromJson(HttpServletRequest request, Class classOfT) { - Either eitherResult; - try { - Either eitherReadJson = readJsonStringFromRequest(request); - if (eitherReadJson.isLeft()) { - eitherResult = convertJsonStringToObject(eitherReadJson.left().value(), classOfT); - } else { - eitherResult = Either.right((Exception) eitherReadJson.right().value()); - } - } catch (Exception e) { - eitherResult = Either.right(e); - } + /** + * Builds an object from a JSON in the POST Body of the request. + */ + public static Either getObjectFromJson(HttpServletRequest request, Class classOfT) { + Either eitherResult; + try { + Either eitherReadJson = readJsonStringFromRequest(request); + if (eitherReadJson.isLeft()) { + eitherResult = convertJsonStringToObject(eitherReadJson.left().value(), classOfT); + } else { + eitherResult = Either.right((Exception) eitherReadJson.right().value()); + } + } catch (Exception e) { + eitherResult = Either.right(e); + } - return eitherResult; - } + return eitherResult; + } - public static Either convertJsonStringToObject(String sentJson, Class classOfT) { - Either eitherResult; - try { - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - T object = gson.fromJson(sentJson, classOfT); - eitherResult = Either.left(object); - } catch (Exception e) { - eitherResult = Either.right(e); - } - return eitherResult; - } + public static Either convertJsonStringToObject(String sentJson, Class classOfT) { + Either eitherResult; + try { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + T object = gson.fromJson(sentJson, classOfT); + eitherResult = Either.left(object); + } catch (Exception e) { + eitherResult = Either.right(e); + } + return eitherResult; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ICategorizedElement.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ICategorizedElement.java new file mode 100644 index 0000000000..0121af702a --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ICategorizedElement.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.common.util; + +import java.util.List; + +public interface ICategorizedElement { + + String getComponentTypeAsString(); + + String getCategoryName(); + + String getSubcategoryName(); + + + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java index b992f7dc7c..fbf94eaaed 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,38 +25,38 @@ import com.google.gson.JsonObject; public class JsonUtils { - public static String toString(JsonElement jsonElement) { + public static String toString(JsonElement jsonElement) { - if (jsonElement == null) { - return null; - } + if (jsonElement == null) { + return null; + } - if (!jsonElement.isJsonNull()) { - if (!jsonElement.isJsonObject()) { - return jsonElement.getAsString(); - } else { - return jsonElement.toString(); - } - } else { - return null; - } + if (!jsonElement.isJsonNull()) { + if (!jsonElement.isJsonObject()) { + return jsonElement.getAsString(); + } else { + return jsonElement.toString(); + } + } else { + return null; + } - } + } - public static boolean containsEntry(JsonObject json, String key) { - return json.get(key) != null; - } + public static boolean containsEntry(JsonObject json, String key) { + return json.get(key) != null; + } - public static boolean isEmptyJson(JsonObject json) { - return json.entrySet().isEmpty(); - } + public static boolean isEmptyJson(JsonObject json) { + return json.entrySet().isEmpty(); + } - public static boolean isEmptyJson(JsonElement json) { - return json.isJsonPrimitive() ? false : JsonUtils.isEmptyJson(json.getAsJsonObject()); - } + public static boolean isEmptyJson(JsonElement json) { + return json.isJsonPrimitive() ? false : JsonUtils.isEmptyJson(json.getAsJsonObject()); + } - public static boolean isJsonNullOrEmpty(JsonObject json) { - return json.isJsonNull() || isEmptyJson(json); - } + public static boolean isJsonNullOrEmpty(JsonObject json) { + return json.isJsonNull() || isEmptyJson(json); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/MethodActivationStatusEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/MethodActivationStatusEnum.java index 758b33bbd3..bba04fa359 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/MethodActivationStatusEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/MethodActivationStatusEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,5 +21,5 @@ package org.openecomp.sdc.common.util; public enum MethodActivationStatusEnum { - SUCCESS, NOT_ALLOWED, FAILED, NOT_FOUND; + SUCCESS, NOT_ALLOWED, FAILED, NOT_FOUND; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/PairUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/PairUtils.java index 7fee13fc0d..eb6c29ce4a 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/PairUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/PairUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/SerializationUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/SerializationUtils.java index 42eb6086fa..cf49718600 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/SerializationUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/SerializationUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,59 +26,54 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInput; -import java.io.ObjectInputStream; -import java.io.ObjectOutput; -import java.io.ObjectOutputStream; +import java.io.*; public class SerializationUtils { - private static Logger log = Logger.getLogger(SerializationUtils.class.getName()); + private static Logger log = Logger.getLogger(SerializationUtils.class.getName()); - private static FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration(); + private static FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration(); - public static Either serialize(Object object) { + public static Either serialize(Object object) { - try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) { - out.writeObject(object); - return Either.left(bos.toByteArray()); - } catch (Exception e) { - log.debug("Failed to serialize object", e); - return Either.right(false); - } - } + try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) { + out.writeObject(object); + return Either.left(bos.toByteArray()); + } catch (Exception e) { + log.debug("Failed to serialize object", e); + return Either.right(false); + } + } - public static Either deserialize(byte[] bytes) { + public static Either deserialize(byte[] bytes) { - try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = new ObjectInputStream(bis)) { - return Either.left(in.readObject()); - } catch (Exception e) { - log.debug("Failed to deserialize object", e); - return Either.right(false); - } - } + try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = new ObjectInputStream(bis)) { + return Either.left(in.readObject()); + } catch (Exception e) { + log.debug("Failed to deserialize object", e); + return Either.right(false); + } + } - public static Either serializeExt(Object object) { - try { - byte[] value = conf.asByteArray(object); - return Either.left(value); - } catch (Exception e) { - return Either.right(false); - } - } + public static Either serializeExt(Object object) { + try { + byte[] value = conf.asByteArray(object); + return Either.left(value); + } catch (Exception e) { + return Either.right(false); + } + } - public static Either deserializeExt(byte[] bytes, Class clazz, String componentName) { - try { - Object object = conf.asObject(bytes); - T castObject = clazz.cast(object); - return Either.left(castObject); - } catch (Exception e) { - log.debug("Failed to deserialize object of type {} and uid {}", clazz, componentName, e); - BeEcompErrorManager.getInstance().logInternalUnexpectedError("DeserializeObjectFromCache", "Failed to deserialize object of type " + clazz, ErrorSeverity.WARNING); - return Either.right(false); - } - } + public static Either deserializeExt(byte[] bytes, Class clazz, String componentName) { + try { + Object object = conf.asObject(bytes); + T castObject = clazz.cast(object); + return Either.left(castObject); + } catch (Exception e) { + log.debug("Failed to deserialize object of type {} and uid {}",clazz,componentName, e); + BeEcompErrorManager.getInstance().logInternalUnexpectedError("DeserializeObjectFromCache", "Failed to deserialize object of type " + clazz, ErrorSeverity.WARNING); + return Either.right(false); + } + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/StreamUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/StreamUtils.java index 88f00f5ee4..2d07069388 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/StreamUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/StreamUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,68 +31,69 @@ import java.util.stream.StreamSupport; /** * Utility Class For Actions On Streams - * + * * @author mshitrit + * */ public final class StreamUtils { - private StreamUtils() { - throw new UnsupportedOperationException(); - } - - /** - * Breaks the stream when the predicate is not met.
    - * Does not evaluate elements after the stream breaks.
    - * This method evaluates the stream.
    - * - * @param stream - * @param predicate - * @return - */ - public static Stream takeWhilePlusOneNoEval(Stream stream, Predicate predicate) { - List results = new ArrayList<>(); - Consumer listAdder = results::add; - stream.map(e -> { - listAdder.accept(e); - return e; - }).filter(e -> !predicate.test(e)).findFirst(); - return results.stream(); - } - - public static Stream takeWhile(Stream stream, Predicate predicate) { - return StreamSupport.stream(takeWhile(stream.spliterator(), predicate), false); - } - - public static Stream takeWhilePlusOne(Stream stream, Predicate predicate) { - return StreamSupport.stream(takeWhile(stream.spliterator(), new StopAfterFailPredicate<>(predicate)), false); - } - - private static Spliterator takeWhile(Spliterator splitr, Predicate predicate) { - return new MySplitIterator<>(splitr, predicate); - } - - public static class MySplitIterator extends AbstractSpliterator implements Spliterator { - private boolean stillGoing = true; - private Spliterator innerItr; - private Predicate innerPred; - - private MySplitIterator(Spliterator splitItr, Predicate pred) { - super(splitItr.estimateSize(), 0); - innerItr = splitItr; - innerPred = pred; - } - - @Override - public boolean tryAdvance(Consumer action) { - boolean canAdvance = true; - if (stillGoing) { - stillGoing = innerItr.tryAdvance(createConsumerWrapper(action)); - } else { - canAdvance = false; - } - return canAdvance; - } - - private Consumer createConsumerWrapper(Consumer action) { + private StreamUtils() { + throw new UnsupportedOperationException(); + } + + /** + * Breaks the stream when the predicate is not met.
    + * Does not evaluate elements after the stream breaks.
    + * This method evaluates the stream.
    + * + * @param stream + * @param predicate + * @return + */ + public static Stream takeWhilePlusOneNoEval(Stream stream, Predicate predicate) { + List results = new ArrayList<>(); + Consumer listAdder = results::add; + stream.map(e -> { + listAdder.accept(e); + return e; + }).filter(e -> !predicate.test(e)).findFirst(); + return results.stream(); + } + + public static Stream takeWhile(Stream stream, Predicate predicate) { + return StreamSupport.stream(takeWhile(stream.spliterator(), predicate), false); + } + + public static Stream takeWhilePlusOne(Stream stream, Predicate predicate) { + return StreamSupport.stream(takeWhile(stream.spliterator(), new StopAfterFailPredicate<>(predicate)), false); + } + + private static Spliterator takeWhile(Spliterator splitr, Predicate predicate) { + return new MySplitIterator<>(splitr, predicate); + } + + public static class MySplitIterator extends AbstractSpliterator implements Spliterator { + boolean stillGoing = true; + private Spliterator innerItr; + private Predicate innerPred; + + private MySplitIterator(Spliterator splitItr, Predicate pred) { + super(splitItr.estimateSize(), 0); + innerItr = splitItr; + innerPred = pred; + } + + @Override + public boolean tryAdvance(Consumer action) { + boolean canAdvance = true; + if (stillGoing) { + stillGoing = innerItr.tryAdvance(createConsumerWrapper(action)); + } else { + canAdvance = false; + } + return canAdvance; + } + + private Consumer createConsumerWrapper(Consumer action) { return new Consumer() { @Override @@ -104,31 +105,31 @@ public final class StreamUtils { } }; - } - - } - - public static class StopAfterFailPredicate implements Predicate { - private boolean hasNotFailed; - private Predicate innerPredicate; - - private StopAfterFailPredicate(Predicate pred) { - hasNotFailed = true; - innerPredicate = pred; - } - - @Override - public boolean test(T t) { - boolean isPassed; - if (hasNotFailed) { - isPassed = true; - hasNotFailed = innerPredicate.test(t); - } else { - isPassed = false; - } - return isPassed; - } - - } + } + + } + + public static class StopAfterFailPredicate implements Predicate { + boolean hasNotFailed; + Predicate innerPredicate; + + private StopAfterFailPredicate(Predicate pred) { + hasNotFailed = true; + innerPredicate = pred; + }; + + @Override + public boolean test(T t) { + boolean isPassed; + if (hasNotFailed) { + isPassed = true; + hasNotFailed = innerPredicate.test(t); + } else { + isPassed = false; + } + return isPassed; + } + + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ThreadLocalsHolder.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ThreadLocalsHolder.java index dcba5711d1..e14c98ee8f 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ThreadLocalsHolder.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ThreadLocalsHolder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,39 +20,77 @@ package org.openecomp.sdc.common.util; +import org.openecomp.sdc.common.api.FilterDecisionEnum; +import org.openecomp.sdc.common.datastructure.UserContext; + public class ThreadLocalsHolder { - private static final ThreadLocal UUID_THREAD_LOCAL = new ThreadLocal<>(); - private static final ThreadLocal REQUEST_START_TIME_THREAD_LOCAL = new ThreadLocal<>(); - private static final ThreadLocal IS_MDC_PROCESSED_THREAD_LOCAL = ThreadLocal.withInitial(() -> false); + private static final ThreadLocal uuidThreadLocal = new ThreadLocal<>(); + private static final ThreadLocal requestStartTimeThreadLocal = new ThreadLocal<>(); + private static final ThreadLocal apiType = new ThreadLocal<>(); + private static final ThreadLocal isMdcProcessedThreadLocal = new ThreadLocal() { + @Override + protected Boolean initialValue() { + return false; + } + }; - public static void setMdcProcessed(Boolean isMdcProcessed) { - IS_MDC_PROCESSED_THREAD_LOCAL.set(isMdcProcessed); - } - public static void setUuid(String uuid) { - UUID_THREAD_LOCAL.set(uuid); - } + private static final ThreadLocal userContextThreadLocal = new ThreadLocal<>(); - public static void setRequestStartTime(Long requestStartTime) { - REQUEST_START_TIME_THREAD_LOCAL.set(requestStartTime); - } + public static final UserContext getUserContext() {return userContextThreadLocal.get(); } - public static String getUuid() { - return UUID_THREAD_LOCAL.get(); - } + public static void setUserContext(UserContext userContext) {userContextThreadLocal.set(userContext); } - public static Long getRequestStartTime() { - return REQUEST_START_TIME_THREAD_LOCAL.get(); - } + public static void setMdcProcessed(Boolean isMdcProcessed) { + isMdcProcessedThreadLocal.set(isMdcProcessed); + } - public static Boolean isMdcProcessed() { - return IS_MDC_PROCESSED_THREAD_LOCAL.get(); - } + public static void setUuid(String uuid) { + uuidThreadLocal.set(uuid); + } + + public static void setRequestStartTime(Long requestStartTime) { + requestStartTimeThreadLocal.set(requestStartTime); + } - public static void cleanup() { - UUID_THREAD_LOCAL.remove(); - REQUEST_START_TIME_THREAD_LOCAL.remove(); - IS_MDC_PROCESSED_THREAD_LOCAL.remove(); + public static String getUuid() { + return uuidThreadLocal.get(); + } + + public static Long getRequestStartTime() { + return requestStartTimeThreadLocal.get(); + } + + public static Boolean isMdcProcessed() { + return isMdcProcessedThreadLocal.get(); + } + + public static void cleanup() { + uuidThreadLocal.remove(); + requestStartTimeThreadLocal.remove(); + isMdcProcessedThreadLocal.remove(); + userContextThreadLocal.remove(); + apiType.remove(); + } + + public static FilterDecisionEnum getApiType() { + return apiType.get(); + } + public static void setApiType(FilterDecisionEnum filterDecisionEnum) { + apiType.set(filterDecisionEnum); + } + + + public static boolean isInternalRequest() { + if (getApiType().equals(FilterDecisionEnum.INTERNAL)){ + return true; + } else return false; } + + public static boolean isExternalRequest() { + if (getApiType().equals(FilterDecisionEnum.EXTERNAL)){ + return true; + } else return false; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java index 988f215a72..6183d42417 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java @@ -21,365 +21,397 @@ package org.openecomp.sdc.common.util; import com.google.common.base.CharMatcher; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.text.WordUtils; import org.apache.commons.validator.routines.UrlValidator; import org.jsoup.Jsoup; +import org.jsoup.helper.StringUtil; import org.jsoup.safety.Whitelist; -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.regex.Pattern; public class ValidationUtils { - public static final Integer COMPONENT_NAME_MAX_LENGTH = 1024; - public static final Pattern COMPONENT_NAME_PATTERN = Pattern - .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (COMPONENT_NAME_MAX_LENGTH - 1) + "}$"); - public static final Integer ADDITIONAL_INFORMATION_KEY_MAX_LENGTH = 50; - public static final Pattern ADDITIONAL_INFORMATION_KEY_PATTERN = Pattern - .compile("^[\\w\\s\\.\\-\\_]{1," + COMPONENT_NAME_MAX_LENGTH + "}$"); - public static final Integer RSI_NAME_MAX_LENGTH = 1024; - public static final Pattern RSI_NAME_PATTERN = Pattern - .compile("^[\\w \\s\\.\\-\\_\\:\\+]{1," + RSI_NAME_MAX_LENGTH + "}$"); - public static final Integer COMMENT_MAX_LENGTH = 256; - - public static final Integer ICON_MAX_LENGTH = 25; - public static final Pattern ICON_PATTERN = Pattern.compile("^[\\w\\-]{1," + ICON_MAX_LENGTH + "}$"); - public static final Integer PROJECT_CODE_MAX_LEGTH = 50; - public static final Pattern PROJECT_CODE_PATTERN = Pattern.compile("^[\\s\\w_.-]{5,50}$"); - - public static final Integer CONNTACT_ID_MAX_LENGTH = 50; - public static final Pattern CONTACT_ID_PATTERN = Pattern.compile("^[\\s\\w_.-]{1,50}$"); - public static final Pattern OCTET_PATTERN = Pattern.compile("%[a-fA-F0-9]{2}"); - public static final Pattern NONE_UTF8_PATTERN = Pattern.compile("[^\\x00-\\x7F]+"); - public static final Pattern URL_INVALIDE_PATTERN = Pattern.compile("[,#?&@$<>~^`\\\\\\[\\]{}|\")(*!+=;%]+"); // ,#?&@$<>~^`\\[]{}|")(*! - - public static final Pattern ENGLISH_PATTERN = Pattern.compile("^[\\p{Graph}\\x20]+$"); - public static final Integer COMPONENT_DESCRIPTION_MAX_LENGTH = 1024; - public static final Integer SERVICE_TYPE_MAX_LENGTH = 400; - public static final Integer SERVICE_ROLE_MAX_LENGTH = 400; - - public static final Integer TAG_MAX_LENGTH = 1024; - public static final Integer TAG_LIST_MAX_LENGTH = 1024; - public static final Integer VENDOR_NAME_MAX_LENGTH = 60; - public static final Pattern VENDOR_NAME_PATTERN = Pattern - .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$"); - public static final Integer VENDOR_RELEASE_MAX_LENGTH = 25; - public static final Pattern VENDOR_RELEASE_PATTERN = Pattern - .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$"); - public static final Integer RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH = 65; - - public static final Pattern CLEAN_FILENAME_PATTERN = Pattern.compile("[\\x00-\\x1f\\x80-\\x9f\\x5c/\\*:|\"/]+"); - - public static final Pattern DASH_PATTERN = Pattern.compile("[-]+"); - public static final Pattern UNDERSCORE_PATTERN = Pattern.compile("[_]+"); - public static final Pattern PLUS_PATTERN = Pattern.compile("[+]+"); - public static final Pattern SPACE_PATTERN = Pattern.compile("[ ]+"); - public static final Pattern AMP_PATTERN = Pattern.compile("[&]+"); - public static final Pattern DOT_PATTERN = Pattern.compile("[\\.]+"); - public static final Pattern APOST_PATTERN = Pattern.compile("[']+"); - public static final Pattern HASHTAG_PATTERN = Pattern.compile("[#]+"); - public static final Pattern EQUAL_PATTERN = Pattern.compile("[=]+"); - public static final Pattern COLON_PATTERN = Pattern.compile("[:]+"); - public static final Pattern AT_PATTERN = Pattern.compile("[@]+"); - public static final Pattern AND_PATTERN = Pattern.compile(" [aA][Nn][Dd] "); - public static final Set CATEGORY_CONJUNCTIONS = new HashSet<>( - Arrays.asList("of", "to", "for", "as", "a", "an", "the")); - - public static final Pattern COST_PATTERN = Pattern.compile("^[0-9]{1,5}\\.[0-9]{1,3}$"); - public static final Pattern ARTIFACT_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9 \\-+]+$"); - public static final Integer ARTIFACT_LABEL_LENGTH = 255; - public static final Pattern ARTIFACT_DISPLAY_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$"); - public static final Pattern CATEGORY_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$"); - public static final Integer CATEGORY_LABEL_MIN_LENGTH = 3; - public static final Integer CATEGORY_LABEL_MAX_LENGTH = 25; - - public static final Pattern COMPONENT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_]+"); - public static final Pattern COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-]+"); - public static final Pattern PRODUCT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_&=#@':\\[\\]\\+]+"); - public static final Integer CONSUMER_NAME_MAX_LENGTH = 255; - // public static final Pattern CONSUMER_NAME_PATTERN = - // Pattern.compile("^[\\w]{1}?[\\w\\.\\-]{0," + CONSUMER_NAME_MAX_LENGTH + - // "}?$"); - public static final Pattern CONSUMER_NAME_PATTERN = Pattern.compile("^[\\w]+[\\w\\.\\-]*$"); - public static final Integer CONSUMER_SALT_LENGTH = 32; - public static final Integer CONSUMER_PASSWORD_LENGTH = 64; - public static final Pattern CONSUMER_PASS_SALT_PATTERN = Pattern.compile("^[a-z0-9]+$"); - public static final Pattern FLOAT_PATTERN = Pattern.compile("^[\\d]+[\\.]{1}[\\d]+$"); - public static final Pattern CERTIFIED_VERSION_PATTERN = Pattern.compile("^[1-9][0-9]*\\.0$"); - public static final Pattern MINOR_VERSION_PATTERN = Pattern.compile("^0\\.[1-9][0-9]*$"); - public static final Pattern TAGS_PATTERN = Pattern.compile("<[^><]*>"); - - public static final Integer ARTIFACT_NAME_LENGTH = 255; - public static final Integer API_URL_LENGTH = 100; - public static final Integer ARTIFACT_DESCRIPTION_MAX_LENGTH = 256; - - public static final Integer PRODUCT_FULL_NAME_MIN_LENGTH = 4; - public static final Integer PRODUCT_FULL_NAME_MAX_LENGTH = 100; - public static final Integer FORWARDING_PATH_NAME_MAX_LENGTH = 100; - public static final Pattern FORWARDING_PATH_NAME_PATTERN = Pattern.compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (FORWARDING_PATH_NAME_MAX_LENGTH - 1) + "}$"); - - public static final Integer POLICY_MAX_LENGTH = 1024; - public static final Pattern POLICY_NAME_PATTERN = Pattern - .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (POLICY_MAX_LENGTH - 1) + "}$"); - - public static boolean validateArtifactLabel(String label) { - return ARTIFACT_LABEL_PATTERN.matcher(label).matches(); - } - - public static boolean validateArtifactDisplayName(String displayName) { - return ARTIFACT_DISPLAY_NAME_PATTERN.matcher(displayName).matches(); - } - - public static boolean validateCategoryDisplayNameFormat(String label) { - boolean res = true; - if (label != null) { - label = label.trim(); - res = CATEGORY_LABEL_PATTERN.matcher(label).matches(); - } - return res; - } - - public static String normalizeCategoryName4Display(String str) { - if (str != null) { - str = str.trim(); - str = DASH_PATTERN.matcher(str).replaceAll("-"); - str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); - str = AMP_PATTERN.matcher(str).replaceAll("&"); - str = PLUS_PATTERN.matcher(str).replaceAll("+"); - str = DOT_PATTERN.matcher(str).replaceAll("."); - str = APOST_PATTERN.matcher(str).replaceAll("'"); - str = HASHTAG_PATTERN.matcher(str).replaceAll("#"); - str = EQUAL_PATTERN.matcher(str).replaceAll("="); - str = COLON_PATTERN.matcher(str).replaceAll(":"); - str = AT_PATTERN.matcher(str).replaceAll("@"); - str = normaliseWhitespace(str); - str = AND_PATTERN.matcher(str).replaceAll(" & "); - - // Case normalizing - StringBuilder sb = new StringBuilder(); - String[] split = str.split(" "); - for (int i = 0; i < split.length; i++) { - String splitted = split[i]; - String lowerCase = splitted.toLowerCase(); - // BANK OF AMERICA --> BANK of AMERICA ("of" is lowercased), but - // OF BANK OF AMERICA --> OF BANK of AMERICA (first "OF" is not - // lowercased because it's first word) - // Agreed with Ella, 26/11/15 - if ((i > 0) && CATEGORY_CONJUNCTIONS.contains(lowerCase)) { - sb.append(lowerCase); - } else { - sb.append(WordUtils.capitalize(splitted)); - } - sb.append(" "); - } - str = sb.toString().trim(); - } - return str; - } - - public static String normalizeCategoryName4Uniqueness(String str) { - return str.toLowerCase(); - } - - public static boolean validateCategoryDisplayNameLength(String label) { - return (label != null && label.length() >= CATEGORY_LABEL_MIN_LENGTH - && label.length() <= CATEGORY_LABEL_MAX_LENGTH); - } - - public static boolean validateProductFullNameLength(String fullName) { - return (fullName != null && fullName.length() >= PRODUCT_FULL_NAME_MIN_LENGTH - && fullName.length() <= PRODUCT_FULL_NAME_MAX_LENGTH); - } - - public static boolean validateArtifactLabelLength(String label) { - return label.length() > 0 && label.length() <= ARTIFACT_LABEL_LENGTH; - } - - public static boolean validateResourceInstanceNameLength(String resourceInstanceName) { - return resourceInstanceName.length() <= RSI_NAME_MAX_LENGTH; - } - - public static boolean validateResourceInstanceName(String resourceInstanceName) { - return RSI_NAME_PATTERN.matcher(resourceInstanceName).matches(); - } - - public static boolean validateUrlLength(String url) { - return url.length() <= API_URL_LENGTH; - } - - public static boolean validateArtifactNameLength(String artifactName) { - return (artifactName.length() <= ARTIFACT_NAME_LENGTH && artifactName.length() > 0); - } - - public static boolean validateComponentNamePattern(String componentName) { - return COMPONENT_NAME_PATTERN.matcher(componentName).matches(); - } - - public static boolean validateComponentNameLength(String componentName) { - return componentName.length() <= COMPONENT_NAME_MAX_LENGTH; - } - - public static boolean validateIcon(String icon) { - return ICON_PATTERN.matcher(icon).matches(); - } - - public static boolean validateIconLength(String icon) { - return icon.length() <= ICON_MAX_LENGTH; - } - - public static boolean validateProjectCode(String projectCode) { - return PROJECT_CODE_PATTERN.matcher(projectCode).matches(); - } - - public static boolean validateProjectCodeLegth(String projectCode) { - return projectCode.length() <= PROJECT_CODE_MAX_LEGTH; - } - - public static boolean validateContactId(String contactId) { - return CONTACT_ID_PATTERN.matcher(contactId).matches(); - } - - public static boolean validateCost(String cost) { - return COST_PATTERN.matcher(cost).matches(); - } - - public static String removeHtmlTags(String str) { - return Jsoup.clean(str, Whitelist.none()); - } - - public static String removeAllTags(String htmlText) { - - return TAGS_PATTERN.matcher(htmlText).replaceAll("").trim(); - } - - public static String normaliseWhitespace(String str) { - StringBuilder sb = new StringBuilder(str.length()); - appendNormalisedWhitespace(sb, str, false); - return sb.toString(); - } - - private static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading) { - boolean lastWasWhite = false; - boolean reachedNonWhite = false; - - int len = string.length(); - int c; - for (int i = 0; i < len; i += Character.charCount(c)) { - c = string.codePointAt(i); - if (isWhitespace(c)) { - if ((stripLeading && !reachedNonWhite) || lastWasWhite) { - continue; - } - accum.append(' '); - lastWasWhite = true; - } else { - accum.appendCodePoint(c); - lastWasWhite = false; - reachedNonWhite = true; - } - } - } - - private static boolean isWhitespace(int c) { - return c == ' '; - } - - public static String stripOctets(String str) { - return OCTET_PATTERN.matcher(str).replaceAll(""); - } - - public static String removeNoneUtf8Chars(String input) { - return NONE_UTF8_PATTERN.matcher(input).replaceAll(""); - } - - public static boolean validateIsEnglish(String input) { - return ENGLISH_PATTERN.matcher(input).matches(); - } - - public static boolean validateIsAscii(String input) { - - return CharMatcher.ASCII.matchesAllOf(input); - } - - public static String convertHtmlTagsToEntities(String input) { - return StringEscapeUtils.escapeHtml4(input); - } - - public static List removeDuplicateFromList(List list) { - Set hs = new LinkedHashSet<>(list); - list.clear(); - list.addAll(hs); - return list; - - } - - public static boolean validateTagLength(String tag) { - if (tag != null) { - return tag.length() <= TAG_MAX_LENGTH; - } - return false; - } - - public static boolean validateTagListLength(int tagListLength) { - return tagListLength <= TAG_LIST_MAX_LENGTH; - } - - public static boolean validateDescriptionLength(String description) { - return description.length() <= COMPONENT_DESCRIPTION_MAX_LENGTH; - } - - public static boolean validateStringNotEmpty(String value) { - if ((value == null) || (value.isEmpty())) { - return false; - } - return true; - } - - public static boolean validateListNotEmpty(List list) { - if ((list == null) || (list.isEmpty())) { - return false; - } - return true; - } - - public static boolean validateVendorName(String vendorName) { - return VENDOR_NAME_PATTERN.matcher(vendorName).matches(); - } - - public static boolean validateVendorNameLength(String vendorName) { - return vendorName.length() <= VENDOR_NAME_MAX_LENGTH; - } - - public static boolean validateResourceVendorModelNumberLength(String resourceVendorModelNumber) { - return resourceVendorModelNumber.length() <= RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH; - } - - public static boolean validateVendorRelease(String vendorRelease) { - return VENDOR_RELEASE_PATTERN.matcher(vendorRelease).matches(); - } - - public static boolean validateVendorReleaseLength(String vendorRelease) { - return vendorRelease.length() <= VENDOR_RELEASE_MAX_LENGTH; - } - - public static boolean validateServiceTypeLength(String serviceType) { - return serviceType.length() <= SERVICE_TYPE_MAX_LENGTH; - } - - public static boolean validateServiceRoleLength(String serviceRole) { - return serviceRole.length() <= SERVICE_ROLE_MAX_LENGTH; - } - - - public static boolean hasBeenCertified(String version) { - return NumberUtils.toDouble(version) >= 1; - } + public final static Integer COMPONENT_NAME_MAX_LENGTH = 1024; + public final static Pattern COMPONENT_NAME_PATTERN = Pattern + .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (COMPONENT_NAME_MAX_LENGTH-1) + "}$"); + public final static Integer ADDITIONAL_INFORMATION_KEY_MAX_LENGTH = 50; + public final static Pattern ADDITIONAL_INFORMATION_KEY_PATTERN = Pattern + .compile("^[\\w\\s\\.\\-\\_]{1," + COMPONENT_NAME_MAX_LENGTH + "}$"); + public final static Integer RSI_NAME_MAX_LENGTH = 1024; + public final static Pattern RSI_NAME_PATTERN = Pattern + .compile("^[\\w \\s\\.\\-\\_\\:\\+]{1," + RSI_NAME_MAX_LENGTH + "}$"); + public final static Integer COMMENT_MAX_LENGTH = 256; + + public final static Integer ICON_MAX_LENGTH = 25; + public final static Pattern ICON_PATTERN = Pattern.compile("^[\\w\\-]{1," + ICON_MAX_LENGTH + "}$"); + public final static Integer PROJECT_CODE_MAX_LEGTH = 50; + public final static Pattern PROJECT_CODE_PATTERN = Pattern.compile("^[\\s\\w_.-]{5,50}$"); + + // USER_ID format : aannnX (where a=a-z or A-Z, n=0-9, and X=a-z,A-Z, or 0-9) + public final static Integer CONNTACT_ID_MAX_LENGTH = 50; + // public final static Pattern CONTACT_ID_PATTERN = Pattern +// .compile("[mM]{1}[0-9]{5}|[a-zA-Z]{2}[0-9]{4}|[a-zA-Z]{2}[0-9]{3}[a-zA-Z]{1}"); + public final static Pattern CONTACT_ID_PATTERN = Pattern.compile("^[\\s\\w_.-]{1,50}$"); + public final static Pattern OCTET_PATTERN = Pattern.compile("%[a-fA-F0-9]{2}"); + public final static Pattern NONE_UTF8_PATTERN = Pattern.compile("[^\\x00-\\x7F]+"); + public final static Pattern URL_INVALIDE_PATTERN = Pattern.compile("[,#?&@$<>~^`\\\\\\[\\]{}|\")(*!+=;%]+");// ,#?&@$<>~^`\\[]{}|")(*! + + public final static Pattern ENGLISH_PATTERN = Pattern.compile("^[\\p{Graph}\\x20]+$"); + public final static Pattern COMMENT_PATTERN = Pattern.compile("^[\\u0000-\\u00BF]{1,1024}$"); + public final static Pattern SERVICE_METADATA_PATTERN = Pattern.compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]{1,256}"); + public final static Integer COMPONENT_DESCRIPTION_MAX_LENGTH = 1024; + public final static Integer SERVICE_TYPE_MAX_LENGTH = 256; + public final static Integer SERVICE_ROLE_MAX_LENGTH = 256; + public final static Integer SERVICE_FUNCTION_MAX_LENGTH = 256; + public final static Integer SERVICE_NAMING_POLICY_MAX_SIZE = 100; + + public final static Integer TAG_MAX_LENGTH = 1024; + public final static Integer TAG_LIST_MAX_LENGTH = 1024; + public final static Integer VENDOR_NAME_MAX_LENGTH = 60; + public final static Pattern VENDOR_NAME_PATTERN = Pattern + .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$"); + public final static Integer VENDOR_RELEASE_MAX_LENGTH = 25; + public final static Pattern VENDOR_RELEASE_PATTERN = Pattern + .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$"); + public final static Integer RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH = 65; + + public final static Pattern CLEAN_FILENAME_PATTERN = Pattern.compile("[\\x00-\\x1f\\x80-\\x9f\\x5c/\\*:|\"/]+"); + + public final static Pattern DASH_PATTERN = Pattern.compile("[-]+"); + public final static Pattern UNDERSCORE_PATTERN = Pattern.compile("[_]+"); + public final static Pattern PLUS_PATTERN = Pattern.compile("[+]+"); + public final static Pattern SPACE_PATTERN = Pattern.compile("[ ]+"); + public final static Pattern AMP_PATTERN = Pattern.compile("[&]+"); + public final static Pattern DOT_PATTERN = Pattern.compile("[\\.]+"); + public final static Pattern APOST_PATTERN = Pattern.compile("[']+"); + public final static Pattern HASHTAG_PATTERN = Pattern.compile("[#]+"); + public final static Pattern EQUAL_PATTERN = Pattern.compile("[=]+"); + public final static Pattern COLON_PATTERN = Pattern.compile("[:]+"); + public final static Pattern AT_PATTERN = Pattern.compile("[@]+"); + public final static Pattern AND_PATTERN = Pattern.compile(" [aA][Nn][Dd] "); + public final static Set CATEGORY_CONJUNCTIONS = new HashSet<>( + Arrays.asList("of", "to", "for", "as", "a", "an", "the")); + + public final static Pattern COST_PATTERN = Pattern.compile("^[0-9]{1,5}\\.[0-9]{1,3}$"); + public final static Pattern ARTIFACT_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9 \\-+]+$"); + public final static Integer ARTIFACT_LABEL_LENGTH = 255; + public final static Pattern ARTIFACT_DISPLAY_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$"); + public final static Pattern CATEGORY_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$"); + public final static Integer CATEGORY_LABEL_MIN_LENGTH = 3; + public final static Integer CATEGORY_LABEL_MAX_LENGTH = 25; + + public final static Pattern COMPONENT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_]+"); + public final static Pattern COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-]+"); + public final static Pattern PRODUCT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_&=#@':\\[\\]\\+]+"); + public final static Integer CONSUMER_NAME_MAX_LENGTH = 255; + // public final static Pattern CONSUMER_NAME_PATTERN = + // Pattern.compile("^[\\w]{1}?[\\w\\.\\-]{0," + CONSUMER_NAME_MAX_LENGTH + + // "}?$"); + public final static Pattern CONSUMER_NAME_PATTERN = Pattern.compile("^[\\w]+[\\w\\.\\-]*$"); + public final static Integer CONSUMER_SALT_LENGTH = 32; + public final static Integer CONSUMER_PASSWORD_LENGTH = 64; + public final static Pattern CONSUMER_PASS_SALT_PATTERN = Pattern.compile("^[a-z0-9]+$"); + public final static Pattern FLOAT_PATTERN = Pattern.compile("^[\\d]+[\\.]{1}[\\d]+$"); + public final static Pattern CERTIFIED_VERSION_PATTERN = Pattern.compile("^[1-9][0-9]*\\.0$"); + public final static Pattern MINOR_VERSION_PATTERN = Pattern.compile("^0\\.[1-9][0-9]*$"); + public final static Pattern TAGS_PATTERN = Pattern.compile("<[^><]*>"); + public final static Pattern TAG_PATTERN = Pattern.compile("^[\\s\\w_.-]{1,1024}$"); + + public final static Integer ARTIFACT_NAME_LENGTH = 255; + public final static Integer API_URL_LENGTH = 100; + public final static Integer ARTIFACT_DESCRIPTION_MAX_LENGTH = 256; + + public final static Integer PRODUCT_FULL_NAME_MIN_LENGTH = 4; + public final static Integer PRODUCT_FULL_NAME_MAX_LENGTH = 100; + public static final Integer FORWARDING_PATH_NAME_MAX_LENGTH = 100; + public final static Pattern FORWARDING_PATH_NAME_PATTERN = Pattern.compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (FORWARDING_PATH_NAME_MAX_LENGTH-1) + "}$"); + + public final static Integer POLICY_MAX_LENGTH = 1024; + public final static Pattern POLICY_NAME_PATTERN = Pattern + .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (POLICY_MAX_LENGTH-1) + "}$"); + + public static boolean validateArtifactLabel(String label) { + return ARTIFACT_LABEL_PATTERN.matcher(label).matches(); + } + + public static boolean validateArtifactDisplayName(String displayName) { + return ARTIFACT_DISPLAY_NAME_PATTERN.matcher(displayName).matches(); + } + + public static String cleanUpText(String text){ + text = removeNoneUtf8Chars(text); + text = normaliseWhitespace(text); + text = stripOctets(text); + text = removeHtmlTagsOnly(text); + return text; + } + + public static boolean validateTagPattern(String tag) { + return TAG_PATTERN.matcher(tag).matches(); + } + + public static boolean validateServiceMetadata(String metadataField) { + return SERVICE_METADATA_PATTERN.matcher(metadataField).matches(); + } + + public static boolean validateCommentPattern(String comment) { + return COMMENT_PATTERN.matcher(comment).matches(); + } + + public static boolean validateCategoryDisplayNameFormat(String label) { + boolean res = true; + if (label != null) { + label = label.trim(); + res = CATEGORY_LABEL_PATTERN.matcher(label).matches(); + } + return res; + } + + public static String normalizeCategoryName4Display(String str) { + if (str != null) { + str = str.trim(); + str = DASH_PATTERN.matcher(str).replaceAll("-"); + str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); + str = AMP_PATTERN.matcher(str).replaceAll("&"); + str = PLUS_PATTERN.matcher(str).replaceAll("+"); + str = DOT_PATTERN.matcher(str).replaceAll("."); + str = APOST_PATTERN.matcher(str).replaceAll("'"); + str = HASHTAG_PATTERN.matcher(str).replaceAll("#"); + str = EQUAL_PATTERN.matcher(str).replaceAll("="); + str = COLON_PATTERN.matcher(str).replaceAll(":"); + str = AT_PATTERN.matcher(str).replaceAll("@"); + str = normaliseWhitespace(str); + str = AND_PATTERN.matcher(str).replaceAll(" & "); + + // Case normalizing + StringBuilder sb = new StringBuilder(); + String[] split = str.split(" "); + for (int i = 0; i < split.length; i++) { + String splitted = split[i]; + String lowerCase = splitted.toLowerCase(); + // BANK OF AMERICA --> BANK of AMERICA ("of" is lowercased), but + // OF BANK OF AMERICA --> OF BANK of AMERICA (first "OF" is not + // lowercased because it's first word) + // Agreed with Ella, 26/11/15 + if ((i > 0) && CATEGORY_CONJUNCTIONS.contains(lowerCase)) { + sb.append(lowerCase); + } else { + sb.append(WordUtils.capitalize(splitted)); + } + sb.append(" "); + } + str = sb.toString().trim(); + } + return str; + } + + public static String normalizeCategoryName4Uniqueness(String str) { + return str.toLowerCase(); + } + + public static boolean validateCategoryDisplayNameLength(String label) { + return (label != null && label.length() >= CATEGORY_LABEL_MIN_LENGTH + && label.length() <= CATEGORY_LABEL_MAX_LENGTH); + } + + public static boolean validateProductFullNameLength(String fullName) { + return (fullName != null && fullName.length() >= PRODUCT_FULL_NAME_MIN_LENGTH + && fullName.length() <= PRODUCT_FULL_NAME_MAX_LENGTH); + } + + public static boolean validateArtifactLabelLength(String label) { + return label.length() > 0 && label.length() <= ARTIFACT_LABEL_LENGTH; + } + + public static boolean validateResourceInstanceNameLength(String resourceInstanceName) { + return resourceInstanceName.length() <= RSI_NAME_MAX_LENGTH; + } + + public static boolean validateResourceInstanceName(String resourceInstanceName) { + return RSI_NAME_PATTERN.matcher(resourceInstanceName).matches(); + } + + public static boolean validateUrlLength(String url) { + return url.length() <= API_URL_LENGTH; + } + + public static boolean validateArtifactNameLength(String artifactName) { + return (artifactName.length() <= ARTIFACT_NAME_LENGTH && artifactName.length() > 0); + } + + public static boolean validateComponentNamePattern(String componentName) { + return COMPONENT_NAME_PATTERN.matcher(componentName).matches(); + } + + public static boolean validateComponentNameLength(String componentName) { + return componentName.length() <= COMPONENT_NAME_MAX_LENGTH; + } + + public static boolean validateIcon(String icon) { + return ICON_PATTERN.matcher(icon).matches(); + } + + public static boolean validateIconLength(String icon) { + return icon.length() <= ICON_MAX_LENGTH; + } + + public static boolean validateProjectCode(String projectCode) { + return PROJECT_CODE_PATTERN.matcher(projectCode).matches(); + } + + public static boolean validateProjectCodeLegth(String projectCode) { + return projectCode.length() <= PROJECT_CODE_MAX_LEGTH; + } + + public static boolean validateContactId(String contactId) { + return CONTACT_ID_PATTERN.matcher(contactId).matches(); + } + + public static boolean validateCost(String cost) { + return COST_PATTERN.matcher(cost).matches(); + } + + public static String removeHtmlTags(String str) { + return Jsoup.clean(str, Whitelist.none()); + } + + public static String removeAllTags(String htmlText) { + + return TAGS_PATTERN.matcher(htmlText).replaceAll("").trim(); + } + + public static String normaliseWhitespace(String str) { + StringBuilder sb = new StringBuilder(str.length()); + appendNormalisedWhitespace(sb, str, false); + return sb.toString(); + } + + private static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading) { + boolean lastWasWhite = false; + boolean reachedNonWhite = false; + + int len = string.length(); + int c; + for (int i = 0; i < len; i+= Character.charCount(c)) { + c = string.codePointAt(i); + if (isWhitespace(c)) { + if ((stripLeading && !reachedNonWhite) || lastWasWhite) + continue; + accum.append(' '); + lastWasWhite = true; + } + else { + accum.appendCodePoint(c); + lastWasWhite = false; + reachedNonWhite = true; + } + } + } + + private static boolean isWhitespace(int c){ + return c == ' '; + } + + public static String stripOctets(String str) { + return OCTET_PATTERN.matcher(str).replaceAll(""); + } + + public static String removeNoneUtf8Chars(String input) { + return NONE_UTF8_PATTERN.matcher(input).replaceAll(""); + } + + public static boolean validateIsEnglish(String input) { + return ENGLISH_PATTERN.matcher(input).matches(); + } + + public static boolean validateIsAscii(String input) { + + return CharMatcher.ASCII.matchesAllOf(input); + } + + public static String convertHtmlTagsToEntities(String input) { + return StringEscapeUtils.escapeHtml4(input); + } + + public static List removeDuplicateFromList(List list) { + Set hs = new LinkedHashSet<>(list); + list.clear(); + list.addAll(hs); + return list; + + } + + public static boolean validateTagLength(String tag) { + if (tag != null) { + return tag.length() <= TAG_MAX_LENGTH; + } + return false; + } + + public static boolean validateTagListLength(int tagListLength) { + return tagListLength <= TAG_LIST_MAX_LENGTH; + } + + public static boolean validateDescriptionLength(String description) { + return description.length() <= COMPONENT_DESCRIPTION_MAX_LENGTH; + } + + public static boolean validateStringNotEmpty(String value) { + if ((value == null) || (value.isEmpty())) { + return false; + } + return true; + } + + public static boolean validateListNotEmpty(List list) { + if ((list == null) || (list.isEmpty())) { + return false; + } + return true; + } + + public static boolean validateVendorName(String vendorName) { + return VENDOR_NAME_PATTERN.matcher(vendorName).matches(); + } + + public static boolean validateVendorNameLength(String vendorName) { + return vendorName.length() <= VENDOR_NAME_MAX_LENGTH; + } + + public static boolean validateResourceVendorModelNumberLength(String resourceVendorModelNumber) { + return resourceVendorModelNumber.length() <= RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH; + } + + public static boolean validateVendorRelease(String vendorRelease) { + return VENDOR_RELEASE_PATTERN.matcher(vendorRelease).matches(); + } + + public static boolean validateVendorReleaseLength(String vendorRelease) { + return vendorRelease.length() <= VENDOR_RELEASE_MAX_LENGTH; + } + + public static boolean validateServiceTypeLength(String serviceType) { + return serviceType.length() <= SERVICE_TYPE_MAX_LENGTH; + } + + public static boolean validateServiceRoleLength(String serviceRole) { + return serviceRole.length() <= SERVICE_ROLE_MAX_LENGTH; + } + + public static boolean validateServiceFunctionLength(String serviceFunction) { + return serviceFunction.length() <= SERVICE_FUNCTION_MAX_LENGTH; + } + + public static boolean validateServiceNamingPolicyLength(String namingPolicy) { + return namingPolicy.length() <= SERVICE_NAMING_POLICY_MAX_SIZE; + } + public static boolean hasBeenCertified(String version) { + return NumberUtils.toDouble(version) >= 1; + } public static String normaliseComponentName(String name) { String[] split = splitComponentName(name); @@ -389,7 +421,7 @@ public class ValidationUtils { } return sb.toString(); - } + } public static String normalizeComponentInstanceName(String name) { String[] split = splitComponentInstanceName(name); @@ -399,19 +431,19 @@ public class ValidationUtils { } return sb.toString(); - } + } - private static String[] splitComponentName(String name) { - String normalizedName = name.toLowerCase(); - normalizedName = COMPONENT_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); - return normalizedName.split(" "); - } + private static String[] splitComponentName(String name) { + String normalizedName = name.toLowerCase(); + normalizedName = COMPONENT_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); + return normalizedName.split(" "); + } - private static String[] splitComponentInstanceName(String name) { - String normalizedName = name.toLowerCase(); - normalizedName = COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); - return normalizedName.split(" "); - } + private static String[] splitComponentInstanceName(String name) { + String normalizedName = name.toLowerCase(); + normalizedName = COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); + return normalizedName.split(" "); + } public static String convertToSystemName(String name) { String[] split = splitComponentName(name); @@ -423,133 +455,137 @@ public class ValidationUtils { return sb.toString(); } - public static String normalizeFileName(String filename) { - // String[] split = filename.split(Pattern.quote(File.separator)); - // String name = ""; - // - // name = split[split.length - 1]; - return cleanFileName(filename); - - } - - private static String cleanFileName(String str) { - str = CLEAN_FILENAME_PATTERN.matcher(str).replaceAll(""); - str = normaliseWhitespace(str); - str = SPACE_PATTERN.matcher(str).replaceAll("-"); - str = DASH_PATTERN.matcher(str).replaceAll("-"); - str = StringUtils.strip(str, "-_ ."); - - return str; - } - - public static boolean validateUrl(String url) { - - UrlValidator urlValidator = new UrlValidator(); - if (!urlValidator.isValid(url)) { - return false; - } - if (NONE_UTF8_PATTERN.matcher(url).find()) { - return false; - } - - if (URL_INVALIDE_PATTERN.matcher(url).find()) { - return false; - } - return true; - - } - - public static String cleanArtifactDisplayName(String strIn) { - String str = DASH_PATTERN.matcher(strIn).replaceAll("-"); - str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); - str = PLUS_PATTERN.matcher(str).replaceAll("+"); - str = normaliseWhitespace(str); - str = str.trim(); - // str = str.replaceAll(" ", ""); - - return str; - } - - public static String normalizeArtifactLabel(String strIn) { - - String str = DASH_PATTERN.matcher(strIn).replaceAll(""); - str = UNDERSCORE_PATTERN.matcher(str).replaceAll(""); - str = PLUS_PATTERN.matcher(str).replaceAll(""); - str = SPACE_PATTERN.matcher(str).replaceAll(""); - str = DOT_PATTERN.matcher(str).replaceAll(""); - str = str.toLowerCase(); - - return str; - } - - public static boolean validateAdditionalInformationKeyName(String str) { - return ADDITIONAL_INFORMATION_KEY_PATTERN.matcher(str).matches(); - } - - public static String normalizeAdditionalInformation(String str) { - if (str != null) { - str = DASH_PATTERN.matcher(str).replaceAll("-"); - str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); - str = normaliseWhitespace(str); - } - return str; - } - - public static boolean validateLength(String str, int length) { - if (str == null) { - return true; - } - return str.length() <= length; - } - - public static boolean validateConsumerName(String consumerName) { - return CONSUMER_NAME_PATTERN.matcher(consumerName).matches(); - } - - public static boolean isUTF8Str(String str) { - if (NONE_UTF8_PATTERN.matcher(str).find()) { - return false; - } - return true; - } - - public static boolean validateConsumerPassSalt(String consumerSalt) { - return CONSUMER_PASS_SALT_PATTERN.matcher(consumerSalt).matches(); - } - - public static boolean isFloatNumber(String number) { - return FLOAT_PATTERN.matcher(number).matches(); - } - - public static boolean validateCertifiedVersion(String version) { - return (version != null && CERTIFIED_VERSION_PATTERN.matcher(version).matches()); - } - - public static boolean validateMinorVersion(String version) { - return (version != null && MINOR_VERSION_PATTERN.matcher(version).matches()); - } - - public static String normaliseProductName(String name) { - String[] split = splitComponentName(PRODUCT_NAME_DELIMETER_PATTERN, name); - StringBuilder sb = new StringBuilder(); - for (String splitElement : split) { - sb.append(splitElement); - } - return sb.toString(); - - } - - private static String[] splitComponentName(Pattern pattern, String name) { - String normalizedName = name.toLowerCase(); - normalizedName = pattern.matcher(normalizedName).replaceAll(" "); - return normalizedName.split(" "); - } - - public static String removeHtmlTagsOnly(String htmlText) { - return HtmlCleaner.stripHtml(htmlText, false); - } - - public static boolean validateForwardingPathNamePattern(String forwardingPathName) { - return FORWARDING_PATH_NAME_PATTERN.matcher(forwardingPathName).matches(); - } + public static String normalizeFileName(String filename) { + // String[] split = filename.split(Pattern.quote(File.separator)); + // String name = ""; + // + // name = split[split.length - 1]; + return cleanFileName(filename); + + } + + private static String cleanFileName(String str) { + str = CLEAN_FILENAME_PATTERN.matcher(str).replaceAll(""); + str = normaliseWhitespace(str); + str = SPACE_PATTERN.matcher(str).replaceAll("-"); + str = DASH_PATTERN.matcher(str).replaceAll("-"); + str = StringUtils.strip(str, "-_ ."); + + return str; + } + + public static boolean validateUrl(String url) { + + UrlValidator urlValidator = new UrlValidator(); + if (!urlValidator.isValid(url)) { + return false; + } + if (NONE_UTF8_PATTERN.matcher(url).find()) { + return false; + } + + if (URL_INVALIDE_PATTERN.matcher(url).find()) { + return false; + } + return true; + + } + + public static String cleanArtifactDisplayName(String strIn) { + String str = DASH_PATTERN.matcher(strIn).replaceAll("-"); + str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); + str = PLUS_PATTERN.matcher(str).replaceAll("+"); + str = normaliseWhitespace(str); + str = str.trim(); + // str = str.replaceAll(" ", ""); + + return str; + } + + public static String normalizeArtifactLabel(String strIn) { + + String str = DASH_PATTERN.matcher(strIn).replaceAll(""); + str = UNDERSCORE_PATTERN.matcher(str).replaceAll(""); + str = PLUS_PATTERN.matcher(str).replaceAll(""); + str = SPACE_PATTERN.matcher(str).replaceAll(""); + str = DOT_PATTERN.matcher(str).replaceAll(""); + str = str.toLowerCase(); + + return str; + } + + public static boolean validateAdditionalInformationKeyName(String str) { + return ADDITIONAL_INFORMATION_KEY_PATTERN.matcher(str).matches(); + } + + public static String normalizeAdditionalInformation(String str) { + if (str != null) { + str = DASH_PATTERN.matcher(str).replaceAll("-"); + str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); + str = normaliseWhitespace(str); + } + return str; + } + + public static boolean validateLength(String str, int length) { + if (str == null) { + return true; + } + return str.length() <= length; + } + + public static boolean validateConsumerName(String consumerName) { + return CONSUMER_NAME_PATTERN.matcher(consumerName).matches(); + } + + public static boolean isUTF8Str(String str) { + if (NONE_UTF8_PATTERN.matcher(str).find()) { + return false; + } + return true; + } + + public static boolean validateConsumerPassSalt(String consumerSalt) { + return CONSUMER_PASS_SALT_PATTERN.matcher(consumerSalt).matches(); + } + + public static boolean isFloatNumber(String number) { + return FLOAT_PATTERN.matcher(number).matches(); + } + + public static boolean validateCertifiedVersion(String version) { + return (version != null && CERTIFIED_VERSION_PATTERN.matcher(version).matches()); + } + + public static boolean validateMinorVersion(String version) { + return (version != null && MINOR_VERSION_PATTERN.matcher(version).matches()); + } + + public static boolean validateCategoryIconNotEmpty(List categoryIcons) { + return CollectionUtils.isEmpty(categoryIcons); + } + + public static String normaliseProductName(String name) { + String[] split = splitComponentName(PRODUCT_NAME_DELIMETER_PATTERN, name); + StringBuilder sb = new StringBuilder(); + for (String splitElement : split) { + sb.append(splitElement); + } + return sb.toString(); + + } + + private static String[] splitComponentName(Pattern pattern, String name) { + String normalizedName = name.toLowerCase(); + normalizedName = pattern.matcher(normalizedName).replaceAll(" "); + return normalizedName.split(" "); + } + + public static String removeHtmlTagsOnly(String htmlText) { + return HtmlCleaner.stripHtml(htmlText, false); + } + + public static boolean validateForwardingPathNamePattern(String forwardingPathName) { + return FORWARDING_PATH_NAME_PATTERN.matcher(forwardingPathName).matches(); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java index 801b6c1aaa..b2435de12c 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,16 +21,7 @@ package org.openecomp.sdc.common.util; import org.apache.commons.codec.binary.Base64; -import org.openecomp.sdc.be.config.Configuration.ApplicationL1CacheConfig; -import org.openecomp.sdc.be.config.Configuration.ApplicationL2CacheConfig; -import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; -import org.openecomp.sdc.be.config.Configuration.BeMonitoringConfig; -import org.openecomp.sdc.be.config.Configuration.EcompPortalConfig; -import org.openecomp.sdc.be.config.Configuration.ElasticSearchConfig; -import org.openecomp.sdc.be.config.Configuration.ElasticSearchConfig.IndicesTimeFrequencyEntry; -import org.openecomp.sdc.be.config.Configuration.OnboardingConfig; -import org.openecomp.sdc.be.config.Configuration.SwitchoverDetectorConfig; -import org.openecomp.sdc.be.config.Configuration.ToscaValidatorsConfig; +import org.openecomp.sdc.be.config.Configuration.*; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; import org.openecomp.sdc.be.config.DistributionEngineConfiguration.ComponentArtifactTypesConfig; import org.openecomp.sdc.be.config.DistributionEngineConfiguration.CreateTopicConfig; @@ -57,228 +48,222 @@ import java.util.Map; public class YamlToObjectConverter { - private static Logger log = Logger.getLogger(YamlToObjectConverter.class.getName()); + private static Logger log = Logger.getLogger(YamlToObjectConverter.class.getName()); - private static HashMap yamls = new HashMap<>(); + private static HashMap yamls = new HashMap<>(); - private static Yaml defaultYaml = new Yaml(); + private static Yaml defaultYaml = new Yaml(); - static { + static { - org.yaml.snakeyaml.constructor.Constructor deConstructor = new org.yaml.snakeyaml.constructor.Constructor( - DistributionEngineConfiguration.class); - TypeDescription deDescription = new TypeDescription(DistributionEngineConfiguration.class); - deDescription.putListPropertyType("distributionStatusTopic", DistributionStatusTopicConfig.class); - deDescription.putListPropertyType("distribNotifServiceArtifactTypes", ComponentArtifactTypesConfig.class); - deDescription.putListPropertyType("distribNotifResourceArtifactTypes", ComponentArtifactTypesConfig.class); - deDescription.putListPropertyType("createTopic", CreateTopicConfig.class); - deDescription.putListPropertyType("distributionNotificationTopic", DistributionNotificationTopicConfig.class); - deConstructor.addTypeDescription(deDescription); - Yaml yaml = new Yaml(deConstructor); - yamls.put(DistributionEngineConfiguration.class.getName(), yaml); + org.yaml.snakeyaml.constructor.Constructor deConstructor = new org.yaml.snakeyaml.constructor.Constructor( + DistributionEngineConfiguration.class); + TypeDescription deDescription = new TypeDescription(DistributionEngineConfiguration.class); + deDescription.putListPropertyType("distributionStatusTopic", DistributionStatusTopicConfig.class); + deDescription.putListPropertyType("distribNotifServiceArtifactTypes", ComponentArtifactTypesConfig.class); + deDescription.putListPropertyType("distribNotifResourceArtifactTypes", ComponentArtifactTypesConfig.class); + deDescription.putListPropertyType("createTopic", CreateTopicConfig.class); + deDescription.putListPropertyType("distributionNotificationTopic", DistributionNotificationTopicConfig.class); + deConstructor.addTypeDescription(deDescription); + Yaml yaml = new Yaml(deConstructor); + yamls.put(DistributionEngineConfiguration.class.getName(), yaml); - // FE conf - org.yaml.snakeyaml.constructor.Constructor feConfConstructor = new org.yaml.snakeyaml.constructor.Constructor( - org.openecomp.sdc.fe.config.Configuration.class); - TypeDescription feConfDescription = new TypeDescription(org.openecomp.sdc.fe.config.Configuration.class); - feConfDescription.putListPropertyType("systemMonitoring", FeMonitoringConfig.class); - feConfConstructor.addTypeDescription(feConfDescription); - yamls.put(org.openecomp.sdc.fe.config.Configuration.class.getName(), new Yaml(feConfConstructor)); - - // BE conf - org.yaml.snakeyaml.constructor.Constructor beConfConstructor = new org.yaml.snakeyaml.constructor.Constructor( - org.openecomp.sdc.be.config.Configuration.class); - TypeDescription beConfDescription = new TypeDescription(org.openecomp.sdc.be.config.Configuration.class); - beConfConstructor.addTypeDescription(beConfDescription); - - // systemMonitoring - beConfDescription.putListPropertyType("systemMonitoring", BeMonitoringConfig.class); - - // elasticSearch - beConfDescription.putListPropertyType("elasticSearch", ElasticSearchConfig.class); - TypeDescription esDescription = new TypeDescription(ElasticSearchConfig.class); - esDescription.putListPropertyType("indicesTimeFrequency", IndicesTimeFrequencyEntry.class); - beConfConstructor.addTypeDescription(esDescription); - - // resourceDeploymentArtifacts and serviceDeploymentArtifacts - beConfDescription.putMapPropertyType("resourceDeploymentArtifacts", String.class, - ArtifactTypeConfig.class); - beConfDescription.putMapPropertyType("serviceDeploymentArtifacts", String.class, - ArtifactTypeConfig.class); - - // onboarding - beConfDescription.putListPropertyType("onboarding", OnboardingConfig.class); - - // ecompPortal - beConfDescription.putListPropertyType("ecompPortal", EcompPortalConfig.class); - // switchoverDetector - beConfDescription.putListPropertyType("switchoverDetector", SwitchoverDetectorConfig.class); - - // ApplicationL1Cache - beConfDescription.putListPropertyType("applicationL1Cache", ApplicationL1CacheConfig.class); - - // ApplicationL2Cache - beConfDescription.putListPropertyType("applicationL2Cache", ApplicationL2CacheConfig.class); - - // tosca validators config - beConfDescription.putListPropertyType("toscaValidators", ToscaValidatorsConfig.class); - - yamls.put(org.openecomp.sdc.be.config.Configuration.class.getName(), new Yaml(beConfConstructor)); - - // HEAT deployment artifact - org.yaml.snakeyaml.constructor.Constructor depArtHeatConstructor = new org.yaml.snakeyaml.constructor.Constructor( - DeploymentArtifactHeatConfiguration.class); - PropertyUtils propertyUtils = new PropertyUtils(); - // Skip properties which are found in YAML but not found in POJO - propertyUtils.setSkipMissingProperties(true); - depArtHeatConstructor.setPropertyUtils(propertyUtils); - yamls.put(org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration.class.getName(), - new Yaml(depArtHeatConstructor)); - - } - - private static Yaml getYamlByClassName(Class className) { - - Yaml yaml = yamls.get(className.getName()); - if (yaml == null) { - yaml = defaultYaml; - } - - return yaml; - } - - public T convert(String dirPath, Class className, String configFileName) { - - T config = null; - - try { - - String fullFileName = dirPath + File.separator + configFileName; - - config = convert(fullFileName, className); - - } catch (Exception e) { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Failed to convert yaml file {} to object.", configFileName, e); - } - - return config; - } - - public class MyYamlConstructor extends org.yaml.snakeyaml.constructor.Constructor { - private HashMap> classMap = new HashMap<>(); - - public MyYamlConstructor(Class theRoot) { - super(theRoot); - classMap.put(DistributionEngineConfiguration.class.getName(), DistributionEngineConfiguration.class); - classMap.put(DistributionStatusTopicConfig.class.getName(), DistributionStatusTopicConfig.class); - } - - /* - * This is a modified version of the Constructor. Rather than using a - * class loader to get external classes, they are already predefined - * above. This approach works similar to the typeTags structure in the - * original constructor, except that class information is pre-populated - * during initialization rather than runtime. - * - * @see - * org.yaml.snakeyaml.constructor.Constructor#getClassForNode(org.yaml. - * snakeyaml.nodes.Node) - */ - protected Class getClassForNode(Node node) { - String name = node.getTag().getClassName(); - Class cl = classMap.get(name); - if (cl == null) { - throw new YAMLException("Class not found: " + name); - } else { - return cl; - } - } - } - - public T convert(String fullFileName, Class className) { - - T config = null; - - Yaml yaml = getYamlByClassName(className); - - InputStream in = null; - try { - - File f = new File(fullFileName); - if (!f.exists()) { - log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "The file {} cannot be found. Ignore reading configuration.", fullFileName); - return null; - } - in = Files.newInputStream(Paths.get(fullFileName)); - - config = yaml.loadAs(in, className); - - // System.out.println(config.toString()); - } catch (Exception e) { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Failed to convert yaml file {} to object.", fullFileName, e); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - log.debug("Failed to close input stream", e); - } - } - } - - return config; - } - - public T convert(byte[] fileContents, Class className) { - - T config = null; - - Yaml yaml = getYamlByClassName(className); + // FE conf + org.yaml.snakeyaml.constructor.Constructor feConfConstructor = new org.yaml.snakeyaml.constructor.Constructor( + org.openecomp.sdc.fe.config.Configuration.class); + TypeDescription feConfDescription = new TypeDescription(org.openecomp.sdc.fe.config.Configuration.class); + feConfDescription.putListPropertyType("systemMonitoring", FeMonitoringConfig.class); + feConfConstructor.addTypeDescription(feConfDescription); + yamls.put(org.openecomp.sdc.fe.config.Configuration.class.getName(), new Yaml(feConfConstructor)); + + // BE conf + org.yaml.snakeyaml.constructor.Constructor beConfConstructor = new org.yaml.snakeyaml.constructor.Constructor( + org.openecomp.sdc.be.config.Configuration.class); + TypeDescription beConfDescription = new TypeDescription(org.openecomp.sdc.be.config.Configuration.class); + beConfConstructor.addTypeDescription(beConfDescription); + + // systemMonitoring + beConfDescription.putListPropertyType("systemMonitoring", BeMonitoringConfig.class); - InputStream in = null; - try { - - in = new ByteArrayInputStream(fileContents); - - config = yaml.loadAs(in, className); - - } catch (Exception e) { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Failed to convert yaml file to object", e); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - log.debug("Failed to close input stream", e); - } - } - } - - return config; - } - - public boolean isValidYamlEncoded64(byte[] fileContents) { - log.trace("Received Base64 data - decoding before validating..."); - byte[] decodedFileContents = Base64.decodeBase64(fileContents); - - return isValidYaml(decodedFileContents); - } - - @SuppressWarnings("unchecked") - public boolean isValidYaml(byte[] fileContents) { - try { - - Iterable mappedToscaTemplateIt = defaultYaml.loadAll(new ByteArrayInputStream(fileContents)); - - for (Object o : mappedToscaTemplateIt) { - System.out.println("Loaded object type:" + o.getClass()); - Map map = (Map) o; - } - - } catch (Exception e) { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Failed to convert yaml file to object - yaml is invalid", e); - return false; - } - return true; - } + // resourceDeploymentArtifacts and serviceDeploymentArtifacts + beConfDescription.putMapPropertyType("resourceDeploymentArtifacts", String.class, + ArtifactTypeConfig.class); + beConfDescription.putMapPropertyType("serviceDeploymentArtifacts", String.class, + ArtifactTypeConfig.class); + + // onboarding + beConfDescription.putListPropertyType("onboarding", OnboardingConfig.class); + + // ecompPortal + beConfDescription.putListPropertyType("ecompPortal", EcompPortalConfig.class); + // switchoverDetector + beConfDescription.putListPropertyType("switchoverDetector", SwitchoverDetectorConfig.class); + + // ApplicationL1Cache + beConfDescription.putListPropertyType("applicationL1Cache", ApplicationL1CacheConfig.class); + + // ApplicationL2Cache + beConfDescription.putListPropertyType("applicationL2Cache", ApplicationL2CacheConfig.class); + + // tosca validators config + beConfDescription.putListPropertyType("toscaValidators", ToscaValidatorsConfig.class); + + yamls.put(org.openecomp.sdc.be.config.Configuration.class.getName(), new Yaml(beConfConstructor)); + + // HEAT deployment artifact + org.yaml.snakeyaml.constructor.Constructor depArtHeatConstructor = new org.yaml.snakeyaml.constructor.Constructor( + DeploymentArtifactHeatConfiguration.class); + PropertyUtils propertyUtils = new PropertyUtils(); + // Skip properties which are found in YAML but not found in POJO + propertyUtils.setSkipMissingProperties(true); + depArtHeatConstructor.setPropertyUtils(propertyUtils); + yamls.put(org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration.class.getName(), + new Yaml(depArtHeatConstructor)); + + } + + private static Yaml getYamlByClassName(Class className) { + + Yaml yaml = yamls.get(className.getName()); + if (yaml == null) { + yaml = defaultYaml; + } + + return yaml; + } + + public T convert(String dirPath, Class className, String configFileName) { + + T config = null; + + try { + + String fullFileName = dirPath + File.separator + configFileName; + + config = convert(fullFileName, className); + + } catch (Exception e) { + log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Failed to convert yaml file {} to object.", configFileName,e); + } + + return config; + } + + public class MyYamlConstructor extends org.yaml.snakeyaml.constructor.Constructor { + private HashMap> classMap = new HashMap<>(); + + public MyYamlConstructor(Class theRoot) { + super(theRoot); + classMap.put(DistributionEngineConfiguration.class.getName(), DistributionEngineConfiguration.class); + classMap.put(DistributionStatusTopicConfig.class.getName(), DistributionStatusTopicConfig.class); + } + + /* + * This is a modified version of the Constructor. Rather than using a + * class loader to get external classes, they are already predefined + * above. This approach works similar to the typeTags structure in the + * original constructor, except that class information is pre-populated + * during initialization rather than runtime. + * + * @see + * org.yaml.snakeyaml.constructor.Constructor#getClassForNode(org.yaml. + * snakeyaml.nodes.Node) + */ + protected Class getClassForNode(Node node) { + String name = node.getTag().getClassName(); + Class cl = classMap.get(name); + if (cl == null) + throw new YAMLException("Class not found: " + name); + else + return cl; + } + } + + public T convert(String fullFileName, Class className) { + + T config = null; + + Yaml yaml = getYamlByClassName(className); + + InputStream in = null; + try { + + File f = new File(fullFileName); + if (!f.exists()) { + log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","The file {} cannot be found. Ignore reading configuration.",fullFileName); + return null; + } + in = Files.newInputStream(Paths.get(fullFileName)); + + config = yaml.loadAs(in, className); + + // System.out.println(config.toString()); + } catch (Exception e) { + log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Failed to convert yaml file {} to object.", fullFileName, e); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + log.debug("Failed to close input stream", e); + e.printStackTrace(); + } + } + } + + return config; + } + + public T convert(byte[] fileContents, Class className) { + + T config = null; + + Yaml yaml = getYamlByClassName(className); + + InputStream in = null; + try { + + in = new ByteArrayInputStream(fileContents); + + config = yaml.loadAs(in, className); + + } catch (Exception e) { + log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Failed to convert yaml file to object", e); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + log.debug("Failed to close input stream", e); + e.printStackTrace(); + } + } + } + + return config; + } + + public boolean isValidYamlEncoded64(byte[] fileContents) { + log.trace("Received Base64 data - decoding before validating..."); + byte[] decodedFileContents = Base64.decodeBase64(fileContents); + + return isValidYaml(decodedFileContents); + } + @SuppressWarnings("unchecked") + public boolean isValidYaml(byte[] fileContents) { + try { + + Iterable mappedToscaTemplateIt = defaultYaml.loadAll(new ByteArrayInputStream(fileContents)); + + for (Object o : mappedToscaTemplateIt) { + System.out.println("Loaded object type:" + o.getClass()); + Map map = (Map) o; + } + + } catch (Exception e) { + log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Failed to convert yaml file to object - yaml is invalid", e); + return false; + } + return true; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/AbstractSdncException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/AbstractSdncException.java index 7fac9f33fa..75315a06cc 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/AbstractSdncException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/AbstractSdncException.java @@ -22,6 +22,7 @@ package org.openecomp.sdc.exception; import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.GeneralUtility; import java.util.Arrays; import java.util.Formatter; @@ -30,87 +31,94 @@ import java.util.regex.Pattern; public abstract class AbstractSdncException { - private String messageId; - - private String text; - - private String[] variables; - - private static Logger log = Logger.getLogger(AbstractSdncException.class.getName()); - - private static final Pattern ERROR_PARAM_PATTERN = Pattern.compile("%\\d"); - - public AbstractSdncException() { - } - - public AbstractSdncException(String messageId, String text, String[] variables) { - super(); - this.messageId = messageId; - this.text = text; - this.variables = validateParameters(messageId, text, variables); - } - - private String[] validateParameters(String messageId, String text, String[] variables) { - String[] res = null; - Matcher m = ERROR_PARAM_PATTERN.matcher(text); - int expectedParamsNum = 0; - while (m.find()) { - expectedParamsNum += 1; - } - int actualParamsNum = (variables != null) ? variables.length : 0; - if (actualParamsNum < expectedParamsNum) { - log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", - "Received less parameters than expected for error with messageId {}, expected: {}, actual: {}. Missing parameters are padded with null values.", - messageId, expectedParamsNum, actualParamsNum); - } else if (actualParamsNum > expectedParamsNum) { - log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "", - "Received more parameters than expected for error with messageId {}, expected: {}, actual: {}. Extra parameters are ignored.", - messageId, expectedParamsNum, actualParamsNum); - } - if (variables != null) { - res = Arrays.copyOf(variables, expectedParamsNum); - } - - return res; - } - - public String getMessageId() { - return this.messageId; - } - - public String getText() { - return text; - } - - public String[] getVariables() { - return variables; - } - - public void setMessageId(String messageId) { - this.messageId = messageId; - } - - public void setText(String text) { - this.text = text; - } - - public void setVariables(String[] variables) { - this.variables = variables; - } - - public String getFormattedErrorMessage() { - String res; - if (variables != null && variables.length > 0) { - Formatter formatter = new Formatter(); - try { - res = formatter.format(this.text.replaceAll("%\\d", "%s"), (Object[]) this.variables).toString(); - } finally { - formatter.close(); - } - } else { - res = this.text; - } - return res; - } + private String messageId; + + private String text; + + private final String ecompRequestId; + + private String[] variables; + + private static Logger log = Logger.getLogger(AbstractSdncException.class.getName()); + + private final static Pattern ERROR_PARAM_PATTERN = Pattern.compile("%\\d"); + + public AbstractSdncException() { + this.ecompRequestId = GeneralUtility.getEcompRequestId(); + } + + public AbstractSdncException(String messageId, String text, String[] variables) { + this(); + this.messageId = messageId; + this.text = text; + this.variables = validateParameters(messageId, text, variables); + } + + private String[] validateParameters(String messageId, String text, String[] variables) { + String[] res = null; + Matcher m = ERROR_PARAM_PATTERN.matcher(text); + int expectedParamsNum = 0; + while (m.find()) { + expectedParamsNum += 1; + } + int actualParamsNum = (variables != null) ? variables.length : 0; + if (actualParamsNum < expectedParamsNum) { + log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR,"","", + "Received less parameters than expected for error with messageId {}, expected: {}, actual: {}. Missing parameters are padded with null values.", + messageId, expectedParamsNum, actualParamsNum); + } else if (actualParamsNum > expectedParamsNum) { + log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","", + "Received more parameters than expected for error with messageId {}, expected: {}, actual: {}. Extra parameters are ignored.", + messageId, expectedParamsNum, actualParamsNum); + } + if (variables != null) { + res = Arrays.copyOf(variables, expectedParamsNum); + } + + return res; + } + + public String getMessageId() { + return messageId; + } + + public String getText() { + return text; + } + + public String getEcompRequestId() { + return ecompRequestId; + } + + public String[] getVariables() { + return variables; + } + + public void setMessageId(String messageId) { + this.messageId = messageId; + } + + public void setText(String text) { + this.text = text; + } + + public void setVariables(String[] variables) { + this.variables = variables; + } + + public String getFormattedErrorMessage() { + String res; + if (variables != null && variables.length > 0) { + Formatter formatter = new Formatter(); + try { + res = formatter.format(this.text.replaceAll("%\\d", "%s"), (Object[]) this.variables).toString(); + } finally { + formatter.close(); + } + } else { + res = this.text; + } + return res; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/DeleteLastApplicationEnvironmentException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/DeleteLastApplicationEnvironmentException.java index b9de46640a..ec33b69d82 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/DeleteLastApplicationEnvironmentException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/DeleteLastApplicationEnvironmentException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,13 +22,13 @@ package org.openecomp.sdc.exception; public class DeleteLastApplicationEnvironmentException extends TechnicalException { - private static final long serialVersionUID = -5192834855057177252L; + private static final long serialVersionUID = -5192834855057177252L; - public DeleteLastApplicationEnvironmentException(String message, Throwable cause) { - super(message, cause); - } + public DeleteLastApplicationEnvironmentException(String message, Throwable cause) { + super(message, cause); + } - public DeleteLastApplicationEnvironmentException(String message) { - super(message); - } + public DeleteLastApplicationEnvironmentException(String message) { + super(message); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/DeleteReferencedObjectException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/DeleteReferencedObjectException.java index 28c0d99538..6957e960c3 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/DeleteReferencedObjectException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/DeleteReferencedObjectException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,9 +27,9 @@ package org.openecomp.sdc.exception; * @author Minh Khang VU */ public class DeleteReferencedObjectException extends TechnicalException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public DeleteReferencedObjectException(String message) { - super(message); - } + public DeleteReferencedObjectException(String message) { + super(message); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/FunctionalException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/FunctionalException.java index 8989feb2ef..5bf67484d5 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/FunctionalException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/FunctionalException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,18 +23,19 @@ package org.openecomp.sdc.exception; /** * All functional exception which is related to user input must go here. It's a * checked exception to force error handling and checking. - * + * * @author mkv + * */ public class FunctionalException extends Exception { - private static final long serialVersionUID = 6712845685798792493L; + private static final long serialVersionUID = 6712845685798792493L; - public FunctionalException(String message, Throwable cause) { - super(message, cause); - } + public FunctionalException(String message, Throwable cause) { + super(message, cause); + } - public FunctionalException(String message) { - super(message); - } + public FunctionalException(String message) { + super(message); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/IndexingServiceException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/IndexingServiceException.java index 0e505ff7ff..d8b8518919 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/IndexingServiceException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/IndexingServiceException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,18 +22,18 @@ package org.openecomp.sdc.exception; /** * All errors happened while trying to access to index service - * + * * @author mkv */ public class IndexingServiceException extends TechnicalException { - private static final long serialVersionUID = 8644422735660389058L; + private static final long serialVersionUID = 8644422735660389058L; - public IndexingServiceException(String message, Throwable cause) { - super(message, cause); - } + public IndexingServiceException(String message, Throwable cause) { + super(message, cause); + } - public IndexingServiceException(String message) { - super(message); - } + public IndexingServiceException(String message) { + super(message); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/InvalidArgumentException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/InvalidArgumentException.java index 6de09fd594..ef6cd659e4 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/InvalidArgumentException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/InvalidArgumentException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,13 +21,13 @@ package org.openecomp.sdc.exception; public class InvalidArgumentException extends TechnicalException { - private static final long serialVersionUID = 931646037604062840L; + private static final long serialVersionUID = 931646037604062840L; - public InvalidArgumentException(String message, Throwable cause) { - super(message, cause); - } + public InvalidArgumentException(String message, Throwable cause) { + super(message, cause); + } - public InvalidArgumentException(String message) { - super(message); - } + public InvalidArgumentException(String message) { + super(message); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/NotFoundException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/NotFoundException.java index 6f4d41c582..988325ff3e 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/NotFoundException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/NotFoundException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,14 +22,14 @@ package org.openecomp.sdc.exception; public class NotFoundException extends TechnicalException { - private static final long serialVersionUID = -5838741067731786413L; + private static final long serialVersionUID = -5838741067731786413L; - public NotFoundException(String message, Throwable cause) { - super(message, cause); - } + public NotFoundException(String message, Throwable cause) { + super(message, cause); + } - public NotFoundException(String message) { - super(message); - } + public NotFoundException(String message) { + super(message); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/OkResponseInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/OkResponseInfo.java index 2c5da89eef..78405e0eb1 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/OkResponseInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/OkResponseInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,7 +22,7 @@ package org.openecomp.sdc.exception; public class OkResponseInfo extends AbstractSdncException { - public OkResponseInfo(String messageId, String text, String[] variables) { - super(messageId, text, variables); - } + public OkResponseInfo(String messageId, String text, String[] variables) { + super(messageId, text, variables); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/PolicyException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/PolicyException.java index c557bccad3..8c5c8609b6 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/PolicyException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/PolicyException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,10 +22,10 @@ package org.openecomp.sdc.exception; public class PolicyException extends AbstractSdncException { - public PolicyException(String messageId, String text, String[] variables) { - super(messageId, text, variables); - } + public PolicyException(String messageId, String text, String[] variables) { + super(messageId, text, variables); + } - public PolicyException() { - } + public PolicyException() { + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/ResponseFormat.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/ResponseFormat.java index 59d30d5180..109164d07d 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/ResponseFormat.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/ResponseFormat.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,169 +22,171 @@ package org.openecomp.sdc.exception; /** * Nested POJOs to express required JSON format of the error - * + * * { "requestError": { "serviceException": { "messageId": "", "text": "", * "variables": [] } } } - * + * + * * @author paharoni + * */ public class ResponseFormat { - private int status; - private RequestErrorWrapper requestErrorWrapper; - - public ResponseFormat() { - super(); - } - - public ResponseFormat(int status) { - super(); - this.status = status; - } - - public void setStatus(int status) { - this.status = status; - } - - public Integer getStatus() { - return status; - } - - public RequestErrorWrapper getRequestError() { - return requestErrorWrapper; - } - - public void setRequestError(RequestErrorWrapper requestErrorWrapper) { - this.requestErrorWrapper = requestErrorWrapper; - } - - public void setPolicyException(PolicyException policyException) { - this.requestErrorWrapper = new RequestErrorWrapper(new RequestError()); - requestErrorWrapper.setPolicyException(policyException); - } - - public void setServiceException(ServiceException serviceException) { - this.requestErrorWrapper = new RequestErrorWrapper(new RequestError()); - requestErrorWrapper.setServiceException(serviceException); - } - - public void setOkResponseInfo(OkResponseInfo okResponseInfo) { - this.requestErrorWrapper = new RequestErrorWrapper(new RequestError()); - requestErrorWrapper.setOkResponseInfo(okResponseInfo); - } - - public String getFormattedMessage() { - if (this.requestErrorWrapper.requestError.okResponseInfo != null) { - return this.requestErrorWrapper.requestError.okResponseInfo.getFormattedErrorMessage(); - } - if (this.requestErrorWrapper.requestError.serviceException != null) { - return this.requestErrorWrapper.requestError.serviceException.getFormattedErrorMessage(); - } - return this.requestErrorWrapper.requestError.policyException.getFormattedErrorMessage(); - } - - public String getText() { - if (this.requestErrorWrapper.requestError.okResponseInfo != null) { - return this.requestErrorWrapper.requestError.okResponseInfo.getText(); - } - if (this.requestErrorWrapper.requestError.serviceException != null) { - return this.requestErrorWrapper.requestError.serviceException.getText(); - } - return this.requestErrorWrapper.requestError.policyException.getText(); - } - - public String[] getVariables() { - if (this.requestErrorWrapper.requestError.okResponseInfo != null) { - return this.requestErrorWrapper.requestError.okResponseInfo.getVariables(); - } - if (this.requestErrorWrapper.requestError.serviceException != null) { - return this.requestErrorWrapper.requestError.serviceException.getVariables(); - } - return this.requestErrorWrapper.requestError.policyException.getVariables(); - } - - public String getMessageId() { - if (this.requestErrorWrapper.requestError.okResponseInfo != null) { - return this.requestErrorWrapper.requestError.okResponseInfo.getMessageId(); - } - if (this.requestErrorWrapper.requestError.serviceException != null) { - return this.requestErrorWrapper.requestError.serviceException.getMessageId(); - } - return this.requestErrorWrapper.requestError.policyException.getMessageId(); - } - - public class RequestErrorWrapper { - private RequestError requestError; - - public RequestErrorWrapper() { - this.requestError = new RequestError(); - } - - public RequestErrorWrapper(RequestError requestError) { - this.requestError = requestError; - } - - public RequestError getRequestError() { - return requestError; - } - - public void setRequestError(RequestError requestError) { - this.requestError = requestError; - } - - public void setPolicyException(PolicyException policyException) { - requestError.setPolicyException(policyException); - } - - public void setServiceException(ServiceException serviceException) { - requestError.setServiceException(serviceException); - } - - public void setOkResponseInfo(OkResponseInfo okResponseInfo) { - requestError.setOkResponseInfo(okResponseInfo); - } - } - - public class RequestError { - @SuppressWarnings("unused") - private PolicyException policyException; - @SuppressWarnings("unused") - private ServiceException serviceException; - @SuppressWarnings("unused") - private OkResponseInfo okResponseInfo; - - public RequestError() { - } - - public PolicyException getPolicyException() { - return policyException; - } - - public ServiceException getServiceException() { - return serviceException; - } - - public OkResponseInfo getOkResponseInfo() { - return okResponseInfo; - } - - public void setPolicyException(PolicyException policyException) { - this.policyException = policyException; - } - - public void setServiceException(ServiceException serviceException) { - this.serviceException = serviceException; - } - - public void setOkResponseInfo(OkResponseInfo okResponseInfo) { - this.okResponseInfo = okResponseInfo; - } - } - - @Override - public String toString() { - return "ResponseFormat[" + "status=" + status + ", requestErrorWrapper=" + requestErrorWrapper + ']'; - } - + private int status; + private RequestErrorWrapper requestErrorWrapper; + + public ResponseFormat() { + super(); + } + + public ResponseFormat(int status) { + super(); + this.status = status; + } + + public void setStatus(int status) { + this.status = status; + } + + public Integer getStatus() { + return status; + } + + public RequestErrorWrapper getRequestError() { + return requestErrorWrapper; + } + + public void setRequestError(RequestErrorWrapper requestErrorWrapper) { + this.requestErrorWrapper = requestErrorWrapper; + } + + public void setPolicyException(PolicyException policyException) { + this.requestErrorWrapper = new RequestErrorWrapper(new RequestError()); + requestErrorWrapper.setPolicyException(policyException); + } + + public void setServiceException(ServiceException serviceException) { + this.requestErrorWrapper = new RequestErrorWrapper(new RequestError()); + requestErrorWrapper.setServiceException(serviceException); + } + + public void setOkResponseInfo(OkResponseInfo okResponseInfo) { + this.requestErrorWrapper = new RequestErrorWrapper(new RequestError()); + requestErrorWrapper.setOkResponseInfo(okResponseInfo); + } + + public String getFormattedMessage() { + if (this.requestErrorWrapper.requestError.okResponseInfo != null) { + return this.requestErrorWrapper.requestError.okResponseInfo.getFormattedErrorMessage(); + } + if (this.requestErrorWrapper.requestError.serviceException != null) { + return this.requestErrorWrapper.requestError.serviceException.getFormattedErrorMessage(); + } + return this.requestErrorWrapper.requestError.policyException.getFormattedErrorMessage(); + } + + public String getText() { + if (this.requestErrorWrapper.requestError.okResponseInfo != null) { + return this.requestErrorWrapper.requestError.okResponseInfo.getText(); + } + if (this.requestErrorWrapper.requestError.serviceException != null) { + return this.requestErrorWrapper.requestError.serviceException.getText(); + } + return this.requestErrorWrapper.requestError.policyException.getText(); + } + + public String[] getVariables() { + if (this.requestErrorWrapper.requestError.okResponseInfo != null) { + return this.requestErrorWrapper.requestError.okResponseInfo.getVariables(); + } + if (this.requestErrorWrapper.requestError.serviceException != null) { + return this.requestErrorWrapper.requestError.serviceException.getVariables(); + } + return this.requestErrorWrapper.requestError.policyException.getVariables(); + } + + public String getMessageId() { + if (this.requestErrorWrapper.requestError.okResponseInfo != null) { + return this.requestErrorWrapper.requestError.okResponseInfo.getMessageId(); + } + if (this.requestErrorWrapper.requestError.serviceException != null) { + return this.requestErrorWrapper.requestError.serviceException.getMessageId(); + } + return this.requestErrorWrapper.requestError.policyException.getMessageId(); + } + + public class RequestErrorWrapper { + private RequestError requestError; + + public RequestErrorWrapper() { + this.requestError = new RequestError(); + } + + public RequestErrorWrapper(RequestError requestError) { + this.requestError = requestError; + } + + public RequestError getRequestError() { + return requestError; + } + + public void setRequestError(RequestError requestError) { + this.requestError = requestError; + } + + public void setPolicyException(PolicyException policyException) { + requestError.setPolicyException(policyException); + } + + public void setServiceException(ServiceException serviceException) { + requestError.setServiceException(serviceException); + } + + public void setOkResponseInfo(OkResponseInfo okResponseInfo) { + requestError.setOkResponseInfo(okResponseInfo); + } + } + + public class RequestError { + @SuppressWarnings("unused") + private PolicyException policyException; + @SuppressWarnings("unused") + private ServiceException serviceException; + @SuppressWarnings("unused") + private OkResponseInfo okResponseInfo; + + public RequestError() { + } + + public PolicyException getPolicyException() { + return policyException; + } + + public ServiceException getServiceException() { + return serviceException; + } + + public OkResponseInfo getOkResponseInfo() { + return okResponseInfo; + } + + public void setPolicyException(PolicyException policyException) { + this.policyException = policyException; + } + + public void setServiceException(ServiceException serviceException) { + this.serviceException = serviceException; + } + + public void setOkResponseInfo(OkResponseInfo okResponseInfo) { + this.okResponseInfo = okResponseInfo; + } + } + + @Override + public String toString() { + return "ResponseFormat[" + "status=" + status + ", requestErrorWrapper=" + requestErrorWrapper + ']'; + } + } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/ServiceException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/ServiceException.java index 4bf3b2ba44..3aae180517 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/ServiceException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/ServiceException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,11 +22,11 @@ package org.openecomp.sdc.exception; public class ServiceException extends AbstractSdncException { - public ServiceException(String messageId, String text, String[] variables) { - super(messageId, text, variables); - } + public ServiceException(String messageId, String text, String[] variables) { + super(messageId, text, variables); + } - public ServiceException() { - } + public ServiceException() { + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/TechnicalException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/TechnicalException.java index 3262a685fa..96ef2f3159 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/TechnicalException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/TechnicalException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,16 +24,17 @@ package org.openecomp.sdc.exception; * Base class for all Alien technical exception * * @author mkv + * */ public abstract class TechnicalException extends RuntimeException { - private static final long serialVersionUID = -9152473183025390161L; + private static final long serialVersionUID = -9152473183025390161L; - public TechnicalException(String message, Throwable cause) { - super(message, cause); - } + public TechnicalException(String message, Throwable cause) { + super(message, cause); + } - public TechnicalException(String message) { - super(message); - } + public TechnicalException(String message) { + super(message); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/VersionConflictException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/VersionConflictException.java index ba0457a16c..a998d6393e 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/VersionConflictException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/VersionConflictException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,9 +25,9 @@ package org.openecomp.sdc.exception; * manner for users */ public class VersionConflictException extends TechnicalException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public VersionConflictException(String message, Throwable cause) { - super(message, cause); - } + public VersionConflictException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java index 85417fb611..b2e58f5766 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java @@ -53,17 +53,15 @@ public class Configuration extends BasicConfiguration { private FeMonitoringConfig systemMonitoring; - private String kibanaHost; - - private Integer kibanaPort; - - private String kibanaProtocol; - private String onboardingForwardContext; private OnboardingConfig onboarding; private DcaeConfig dcae; + + private CookieConfig authCookie; + + private CatalogFacadeMsConfig catalogFacadeMs; /** * be http context */ @@ -80,30 +78,15 @@ public class Configuration extends BasicConfiguration { private int requestTimeout; private List> identificationHeaderFields; private List> optionalHeaderFields; - private List forwardHeaderFields; - - public String getKibanaProtocol() { - return kibanaProtocol; - } - - public void setKibanaProtocol(String kibanaProtocol) { - this.kibanaProtocol = kibanaProtocol; - } - public String getKibanaHost() { - return kibanaHost; - } - - public void setKibanaHost(String kibanaHost) { - this.kibanaHost = kibanaHost; - } + private List forwardHeaderFields; - public Integer getKibanaPort() { - return kibanaPort; + public CatalogFacadeMsConfig getCatalogFacadeMs() { + return catalogFacadeMs; } - public void setKibanaPort(Integer kibanaPort) { - this.kibanaPort = kibanaPort; + public void setCatalogFacadeMs(CatalogFacadeMsConfig catalogFacadeMs) { + this.catalogFacadeMs = catalogFacadeMs; } public FeMonitoringConfig getSystemMonitoring() { @@ -274,6 +257,14 @@ public class Configuration extends BasicConfiguration { this.dcae = dcae; } + public CookieConfig getAuthCookie() { + return authCookie; + } + + public void setAuthCookie(CookieConfig authCookie) { + this.authCookie = authCookie; + } + @Override public String toString() { return new StringBuilder().append(format("backend host: %s%n", beHost)) @@ -288,9 +279,9 @@ public class Configuration extends BasicConfiguration { public static class FeMonitoringConfig { - private Boolean enabled; - private Boolean isProxy; - private Integer probeIntervalInSeconds; + Boolean enabled; + Boolean isProxy; + Integer probeIntervalInSeconds; public Boolean getEnabled() { return enabled; @@ -322,13 +313,13 @@ public class Configuration extends BasicConfiguration { } public static class OnboardingConfig { - private String protocolFe = "http"; - private String hostFe; - private Integer portFe; - private String protocolBe = "http"; - private String hostBe; - private Integer portBe; - private String healthCheckUriFe; + String protocolFe = "http"; + String hostFe; + Integer portFe; + String protocolBe = "http"; + String hostBe; + Integer portBe; + String healthCheckUriFe; public String getProtocolFe() { return protocolFe; @@ -389,10 +380,10 @@ public class Configuration extends BasicConfiguration { public static class DcaeConfig { - private String protocol = "http"; - private String host; - private Integer port; - private String healthCheckUri; + String protocol = "http"; + String host; + Integer port; + String healthCheckUri; public String getProtocol() { return protocol; @@ -427,6 +418,94 @@ public class Configuration extends BasicConfiguration { } } + public static class CookieConfig { + String cookieName = "AuthenticationCookie"; + String path = ""; + String domain = ""; + String securityKey = ""; + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getDomain() { + return domain; + } + + public void setDomain(String domain) { + this.domain = domain; + } + + public String getSecurityKey() {return securityKey; + } + + public void setSecurityKey(String securityKey) { + this.securityKey = securityKey; + } + + public String getCookieName() { + return cookieName; + } + + public void setCookieName(String cookieName) { + this.cookieName = cookieName; + } + } + + public static class CatalogFacadeMsConfig { + String protocol; + String host; + Integer port; + String healthCheckUri; + String path; + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public void setHost(String host) { + this.host = host; + } + + public void setPort(Integer port) { + this.port = port; + } + + public void setHealthCheckUri(String healthCheckUri) { + this.healthCheckUri = healthCheckUri; + } + + public void setPath(String path) { + this.path = path; + } + + public String getProtocol() { + return protocol; + } + + public String getHost() { + return host; + } + + public Integer getPort() { + return port; + } + + public String getHealthCheckUri() { + return healthCheckUri; + } + + public String getPath() { + return path; + } + + + } + public List getHealthStatusExclude() { return healthStatusExclude; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/ConfigurationManager.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/ConfigurationManager.java index 5aa2d1f79d..ed7a2e9817 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/ConfigurationManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/ConfigurationManager.java @@ -27,28 +27,28 @@ import org.openecomp.sdc.common.api.FileChangeCallback; import org.openecomp.sdc.common.config.EcompErrorConfiguration; import org.openecomp.sdc.common.config.IEcompConfigurationManager; import org.openecomp.sdc.common.rest.api.RestConfigurationInfo; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import java.util.HashMap; import java.util.Map; public class ConfigurationManager implements FileChangeCallback, IEcompConfigurationManager { - private ConfigurationSource configurationSource = null; - private static ConfigurationManager instance; - private static Logger logger = LoggerFactory.getLogger(ConfigurationManager.class.getName()); + ConfigurationSource configurationSource = null; + private static ConfigurationManager instance; - public ConfigurationManager(ConfigurationSource configurationSource) { - super(); - this.configurationSource = configurationSource; - loadConfigurationFiles(); - instance = this; - } + private static final Logger log = Logger.getLogger(ConfigurationManager.class.getName()); + + public ConfigurationManager(ConfigurationSource configurationSource) { + super(); + this.configurationSource = configurationSource; + loadConfigurationFiles(); + instance = this; + } - private Map configurations = new HashMap<>(); + Map configurations = new HashMap<>(); - private void loadConfigurationFiles() { + private void loadConfigurationFiles() { loadConfigurationClass(Configuration.class); loadConfigurationClass(RestConfigurationInfo.class); @@ -56,54 +56,54 @@ public class ConfigurationManager implements FileChangeCallback, IEcompConfigura loadConfigurationClass(PluginsConfiguration.class); loadConfigurationClass(WorkspaceConfiguration.class); - } + } - private void loadConfigurationClass(Class clazz) { - ConfigurationListener configurationListener = new ConfigurationListener(clazz, this); + private void loadConfigurationClass(Class clazz) { + ConfigurationListener configurationListener = new ConfigurationListener(clazz, this); - logger.info("created listener for class {}: {}", clazz.getName(), configurationListener); + log.info("created listener for class {}: {}", clazz.getName(), configurationListener); - T object = configurationSource.getAndWatchConfiguration(clazz, configurationListener); + T object = configurationSource.getAndWatchConfiguration(clazz, configurationListener); - configurations.put(getKey(clazz), object); - } + configurations.put(getKey(clazz), object); + } - private String getKey(Class class1) { + private String getKey(Class class1) { - return class1.getSimpleName(); + return class1.getSimpleName(); - } + } - public Configuration getConfiguration() { + public Configuration getConfiguration() { - return (Configuration) configurations.get(getKey(Configuration.class)); + return (Configuration) configurations.get(getKey(Configuration.class)); - } + } - public RestConfigurationInfo getRestClientConfiguration() { + public RestConfigurationInfo getRestClientConfiguration() { - return (RestConfigurationInfo) configurations.get(getKey(RestConfigurationInfo.class)); + return (RestConfigurationInfo) configurations.get(getKey(RestConfigurationInfo.class)); - } + } - @Override - public EcompErrorConfiguration getEcompErrorConfiguration() { + @Override + public EcompErrorConfiguration getEcompErrorConfiguration() { - return (EcompErrorConfiguration) configurations.get(getKey(EcompErrorConfiguration.class)); + return (EcompErrorConfiguration) configurations.get(getKey(EcompErrorConfiguration.class)); - } + } - public PluginsConfiguration getPluginsConfiguration() { + public PluginsConfiguration getPluginsConfiguration() { - logger.info("requested plugins configuration and got this:{}", configurations.get(getKey(PluginsConfiguration.class))); + log.info("requested plugins configuration and got this:{}", configurations.get(getKey(PluginsConfiguration.class))); - return (PluginsConfiguration) configurations.get(getKey(PluginsConfiguration.class)); - } + return (PluginsConfiguration) configurations.get(getKey(PluginsConfiguration.class)); + } public WorkspaceConfiguration getWorkspaceConfiguration() { - logger.info("requested plugins configuration and got this:{}", configurations.get(getKey(WorkspaceConfiguration.class))); + log.info("requested plugins configuration and got this:{}", configurations.get(getKey(WorkspaceConfiguration.class))); return (WorkspaceConfiguration) configurations.get(getKey(WorkspaceConfiguration.class)); } @@ -111,22 +111,34 @@ public class ConfigurationManager implements FileChangeCallback, IEcompConfigura public Configuration getConfigurationAndWatch(ConfigurationListener configurationListener) { - if (configurationListener != null) { + if (configurationListener != null) { - configurationSource.addWatchConfiguration(Configuration.class, configurationListener); + configurationSource.addWatchConfiguration(Configuration.class, configurationListener); - } - return (Configuration) configurations.get(getKey(Configuration.class)); + } + return (Configuration) configurations.get(getKey(Configuration.class)); - } + } - public void reconfigure(BasicConfiguration obj) { } + public void reconfigure(BasicConfiguration obj) { + // + // if (obj != null) { + // + // if (obj instanceof Configuration) { + // configurations.put(getKey(Configuration.class), obj); + // } + // + // if (obj instanceof EcompErrorConfiguration) { + // configurations.put(getKey(EcompErrorConfiguration.class), obj); + // } + // } + } - public static ConfigurationManager getConfigurationManager() { - return instance; - } + public static ConfigurationManager getConfigurationManager() { + return instance; + } - public static void setTestInstance(ConfigurationManager configurationManagerInstance) { - instance = configurationManagerInstance; - } + public static void setTestInstance(ConfigurationManager configurationManagerInstance) { + instance = configurationManagerInstance; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Connection.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Connection.java index 7d681bdba6..7208398525 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Connection.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Connection.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,27 +22,27 @@ package org.openecomp.sdc.fe.config; public class Connection { - private String url; - private int poolSize; + private String url; + private int poolSize; - public String getUrl() { - return url; - } + public String getUrl() { + return url; + } - public void setUrl(String url) { - this.url = url; - } + public void setUrl(String url) { + this.url = url; + } - public int getPoolSize() { - return poolSize; - } + public int getPoolSize() { + return poolSize; + } - public void setPoolSize(int poolSize) { - this.poolSize = poolSize; - } + public void setPoolSize(int poolSize) { + this.poolSize = poolSize; + } - @Override - public String toString() { - return String.format("'%s' with pool of %d", getUrl(), getPoolSize()); - } + @Override + public String toString() { + return String.format("'%s' with pool of %d", getUrl(), getPoolSize()); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/FeEcompErrorManager.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/FeEcompErrorManager.java index 13459713ff..a36293b829 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/FeEcompErrorManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/FeEcompErrorManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,51 +26,51 @@ import org.openecomp.sdc.common.config.IEcompConfigurationManager; public class FeEcompErrorManager extends AbsEcompErrorManager { - private static volatile FeEcompErrorManager instance; - private static ConfigurationManager configurationManager; + private static volatile FeEcompErrorManager instance; + private static ConfigurationManager configurationManager; - private FeEcompErrorManager() { - } + private FeEcompErrorManager() { + }; - public static FeEcompErrorManager getInstance() { - if (instance == null) { + public static FeEcompErrorManager getInstance() { + if (instance == null) { - instance = init(); - } - return instance; - } + instance = init(); + } + return instance; + } - private static synchronized FeEcompErrorManager init() { - if (instance == null) { - instance = new FeEcompErrorManager(); - configurationManager = ConfigurationManager.getConfigurationManager(); - } - return instance; - } + private static synchronized FeEcompErrorManager init() { + if (instance == null) { + instance = new FeEcompErrorManager(); + configurationManager = ConfigurationManager.getConfigurationManager(); + } + return instance; + } - @Override - public IEcompConfigurationManager getConfigurationManager() { - return configurationManager; - } + @Override + public IEcompConfigurationManager getConfigurationManager() { + return configurationManager; + } - public void logFeHealthCheckRecovery(String context) { - processEcompError(context, EcompErrorEnum.FeHealthCheckRecovery); - } + public void logFeHealthCheckRecovery(String context) { + processEcompError(context, EcompErrorEnum.FeHealthCheckRecovery); + } - public void logFeHealthCheckError(String context) { - processEcompError(context, EcompErrorEnum.FeHealthCheckError); - } + public void logFeHealthCheckError(String context) { + processEcompError(context, EcompErrorEnum.FeHealthCheckError); + } - public void logFeHttpLoggingError(String context) { - processEcompError(context, EcompErrorEnum.FeHttpLoggingError); - } + public void logFeHttpLoggingError(String context) { + processEcompError(context, EcompErrorEnum.FeHttpLoggingError); + } - public void logFePortalServletError(String context) { - processEcompError(context, EcompErrorEnum.FePortalServletError); - } + public void logFePortalServletError(String context) { + processEcompError(context, EcompErrorEnum.FePortalServletError); + } - public void logFeHealthCheckGeneralError(String context) { - processEcompError(context, EcompErrorEnum.FeHealthCheckGeneralError); - } + public void logFeHealthCheckGeneralError(String context) { + processEcompError(context, EcompErrorEnum.FeHealthCheckGeneralError); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/PluginsConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/PluginsConfiguration.java index 449c9eaccc..b891c7f85c 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/PluginsConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/PluginsConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -134,17 +134,17 @@ public class PluginsConfiguration extends BasicConfiguration { @Override public String toString() { - return "PluginDisplayOptions[" - + "displayName='" + displayName - + ", displayContext=" + displayContext - + ", displayRoles=" + displayRoles - + ']'; + return "PluginDisplayOptions[" + + "displayName='" + displayName + + ", displayContext=" + displayContext + + ", displayRoles=" + displayRoles + + ']'; } } @Override public String toString() { - return "PluginsConfiguration[" + "pluginsList=" + pluginsList + ", connectionTimeout=" + connectionTimeout + ']'; + return "PluginsConfiguration[" + "pluginsList=" + pluginsList + ", connectionTimeout=" + connectionTimeout +']'; } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/monitoring/FeMonitoringService.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/monitoring/FeMonitoringService.java index 1ac10a2611..78e565e6c3 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/fe/monitoring/FeMonitoringService.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/monitoring/FeMonitoringService.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -35,8 +35,7 @@ import org.openecomp.sdc.common.monitoring.MonitoringEvent; import org.openecomp.sdc.common.monitoring.MonitoringMetricsFetcher; import org.openecomp.sdc.fe.config.Configuration; import org.openecomp.sdc.fe.config.ConfigurationManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import javax.servlet.ServletContext; import java.util.concurrent.Executors; @@ -46,65 +45,64 @@ import java.util.concurrent.TimeUnit; public class FeMonitoringService { - private static final String URL = "%s://%s:%s/sdc2/rest/monitoring"; - private static final int DEFAULT_TIMEOUT = 3000; - private static Logger monitoringLogger = LoggerFactory.getLogger("asdc.fe.monitoring.service"); - private static Logger log = LoggerFactory.getLogger(FeMonitoringService.class.getName()); - private static Gson gson = new GsonBuilder().setPrettyPrinting().create(); + private static final String URL = "%s://%s:%s/sdc2/rest/monitoring"; + private static Logger monitoringLogger = Logger.getLogger("asdc.fe.monitoring.service"); + private static Logger log = Logger.getLogger(FeMonitoringService.class.getName()); + private static Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private class MonitoringScheduledTask implements Runnable { - @Override - public void run() { - monitoringLogger.trace("Executing FE Monitoring Task - Start"); - MonitoringEvent monitoringMetrics = MonitoringMetricsFetcher.getInstance().getMonitoringMetrics(); - processMonitoringEvent(monitoringMetrics); - monitoringLogger.trace("Executing FE Monitoring Task - Status = {}", monitoringMetrics.toString()); - } - } + private class MonitoringScheduledTask implements Runnable { + @Override + public void run() { + monitoringLogger.trace("Executing FE Monitoring Task - Start"); + MonitoringEvent monitoringMetrics = MonitoringMetricsFetcher.getInstance().getMonitoringMetrics(); + processMonitoringEvent(monitoringMetrics); + monitoringLogger.trace("Executing FE Monitoring Task - Status = {}", monitoringMetrics.toString()); + } + } - /** - * This executor will execute the Monitoring task. - */ - private ScheduledExecutorService monitoringExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "FE-Monitoring-Thread"); - } - }); - private ServletContext context; + /** + * This executor will execute the Monitoring task. + */ + ScheduledExecutorService monitoringExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "FE-Monitoring-Thread"); + } + }); + private ServletContext context; - public FeMonitoringService(ServletContext context) { - this.context = context; - } + public FeMonitoringService(ServletContext context) { + this.context = context; + } - public void start(int interval) { - Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) - .getConfiguration(); - if (config.getSystemMonitoring().getEnabled()) { - log.info("FE monitoring service enabled, interval is {} seconds", interval); - this.monitoringExecutor.scheduleAtFixedRate(new MonitoringScheduledTask(), 0, interval, TimeUnit.SECONDS); - } else { - log.info("FE monitoring service is disabled"); - } - } + public void start(int interval) { + Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) + .getConfiguration(); + if (config.getSystemMonitoring().getEnabled()) { + log.info("FE monitoring service enabled, interval is {} seconds", interval); + this.monitoringExecutor.scheduleAtFixedRate(new MonitoringScheduledTask(), 0, interval, TimeUnit.SECONDS); + } else { + log.info("FE monitoring service is disabled"); + } + } - private void processMonitoringEvent(MonitoringEvent monitoringMetrics) { - try { - Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) - .getConfiguration(); - String redirectedUrl = String.format(URL, config.getBeProtocol(), config.getBeHost(), - Constants.HTTPS.equals(config.getBeProtocol()) ? config.getBeSslPort() : config.getBeHttpPort()); + private void processMonitoringEvent(MonitoringEvent monitoringMetrics) { + try { + Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) + .getConfiguration(); + String redirectedUrl = String.format(URL, config.getBeProtocol(), config.getBeHost(), + Constants.HTTPS.equals(config.getBeProtocol()) ? config.getBeSslPort() : config.getBeHttpPort()); - int timeout = DEFAULT_TIMEOUT; - String monitoringMetricsJson = gson.toJson(monitoringMetrics); - HttpEntity myEntity = new StringEntity(monitoringMetricsJson, ContentType.APPLICATION_JSON); - HttpResponse resposne = HttpRequest.post(redirectedUrl, myEntity, new HttpClientConfig(new Timeouts(timeout, timeout))); + int timeout = 3000; + String monitoringMetricsJson = gson.toJson(monitoringMetrics); + HttpEntity myEntity = new StringEntity(monitoringMetricsJson, ContentType.APPLICATION_JSON); + HttpResponse resposne = HttpRequest.post(redirectedUrl, myEntity, new HttpClientConfig(new Timeouts(timeout, timeout))); int beResponseStatus = resposne.getStatusCode(); if (beResponseStatus != HttpStatus.SC_OK) { monitoringLogger.error("Unexpected HTTP response from BE : {}", beResponseStatus); } - } catch (Exception e) { - monitoringLogger.error("Monitoring BE failed with exception ", e); - } - } + } catch (Exception e) { + monitoringLogger.error("Monitoring BE failed with exception ", e); + } + } } diff --git a/common-app-api/src/test/java/org/openecomp/sdc/be/config/BeEcompErrorManagerTest.java b/common-app-api/src/test/java/org/openecomp/sdc/be/config/BeEcompErrorManagerTest.java index 4878e8b85f..e12b37c107 100644 --- a/common-app-api/src/test/java/org/openecomp/sdc/be/config/BeEcompErrorManagerTest.java +++ b/common-app-api/src/test/java/org/openecomp/sdc/be/config/BeEcompErrorManagerTest.java @@ -87,18 +87,6 @@ public class BeEcompErrorManagerTest { testSubject.logBeHealthCheckJanusGraphRecovery(context); } - - @Test - public void testLogBeHealthCheckElasticSearchRecovery() throws Exception { - BeEcompErrorManager testSubject; - String context = ""; - - // default test - testSubject = createTestSubject(); - testSubject.logBeHealthCheckElasticSearchRecovery(context); - } - - @Test public void testLogBeHealthCheckUebClusterRecovery() throws Exception { BeEcompErrorManager testSubject; @@ -142,18 +130,6 @@ public class BeEcompErrorManagerTest { testSubject.logBeHealthCheckJanusGraphError(context); } - - @Test - public void testLogBeHealthCheckElasticSearchError() throws Exception { - BeEcompErrorManager testSubject; - String context = ""; - - // default test - testSubject = createTestSubject(); - testSubject.logBeHealthCheckElasticSearchError(context); - } - - @Test public void testLogBeHealthCheckUebClusterError() throws Exception { BeEcompErrorManager testSubject; diff --git a/common-app-api/src/test/java/org/openecomp/sdc/be/config/ConfigurationManagerTest.java b/common-app-api/src/test/java/org/openecomp/sdc/be/config/ConfigurationManagerTest.java index a3d34e5ce2..8c5ce2a088 100644 --- a/common-app-api/src/test/java/org/openecomp/sdc/be/config/ConfigurationManagerTest.java +++ b/common-app-api/src/test/java/org/openecomp/sdc/be/config/ConfigurationManagerTest.java @@ -80,15 +80,9 @@ public class ConfigurationManagerTest { @Test public void testGetDistributionEngineConfiguration() { assertEquals(configurationManager.getDistributionEngineConfiguration(), - ConfigurationManager.getConfigurationManager().getConfigurations() + ConfigurationManager.getConfigurationManager().configurations .get(DistributionEngineConfiguration.class.getSimpleName())); } - @Test - public void testGetNeo4jErrorsConfiguration() { - assertEquals(configurationManager.getNeo4jErrorsConfiguration(), - ConfigurationManager.getConfigurationManager().getConfigurations() - .get(Neo4jErrorsConfiguration.class.getSimpleName())); - } private class TestConfiguration extends Configuration{} @Test public void testGetConfigurationAndWatch() { diff --git a/common-app-api/src/test/java/org/openecomp/sdc/be/config/ConfigurationTest.java b/common-app-api/src/test/java/org/openecomp/sdc/be/config/ConfigurationTest.java index cb92d355c1..055b41c921 100644 --- a/common-app-api/src/test/java/org/openecomp/sdc/be/config/ConfigurationTest.java +++ b/common-app-api/src/test/java/org/openecomp/sdc/be/config/ConfigurationTest.java @@ -28,9 +28,7 @@ import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetter import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.MatcherAssert.assertThat; - public class ConfigurationTest { - @Test public void validateBean() { assertThat(Configuration.class, allOf( hasValidBeanConstructor(), @@ -44,13 +42,6 @@ public class ConfigurationTest { )); } @Test - public void validateBeanForElasticSearchConfig() { - assertThat(Configuration.ElasticSearchConfig.class, allOf( - hasValidBeanConstructor(), - hasValidGettersAndSettersExcluding() - )); - } - @Test public void validateBeanForCassandrConfig() { assertThat(Configuration.CassandrConfig.class, allOf( hasValidBeanConstructor(), diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/datastructure/ESTimeBasedEventTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/datastructure/ESTimeBasedEventTest.java deleted file mode 100644 index 10da662827..0000000000 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/datastructure/ESTimeBasedEventTest.java +++ /dev/null @@ -1,105 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END============================================ - * =================================================================== - * - */ - -package org.openecomp.sdc.common.datastructure; - -import static org.junit.Assert.assertEquals; - -import java.util.Map; -import org.codehaus.jettison.json.JSONException; -import org.junit.Test; - - -public class ESTimeBasedEventTest { - - private ESTimeBasedEvent createTestSubject() { - return new ESTimeBasedEvent(); - } - - - @Test - public void testCalculateYearIndexSuffix() { - createTestSubject().calculateYearIndexSuffix(); - } - - - @Test - public void testCalculateMonthIndexSuffix() { - createTestSubject().calculateMonthIndexSuffix(); - } - - - @Test - public void testCalculateDayIndexSuffix() { - createTestSubject().calculateDayIndexSuffix(); - } - - - @Test - public void testCalculateHourIndexSuffix() { - createTestSubject().calculateHourIndexSuffix(); - } - - - @Test - public void testCalculateMinuteIndexSuffix() { - createTestSubject().calculateMinuteIndexSuffix(); - } - - - @Test - public void testGetTimestamp() { - createTestSubject().getTimestamp(); - } - - - @Test - public void testSetTimestamp() { - createTestSubject().setTimestamp(""); - } - - - @Test - public void testGetFields() { - createTestSubject().getFields(); - } - - - @Test - public void testSetFields() { - createTestSubject().setFields(null); - } - - @Test - public void testCreateEventFromJson() throws JSONException { - //given - String stringJson = - "{\n \"TIMESTAMP\" : \"2000-05-01 20:00:00.000 z\",\n \"event_type\" : \"activation\" }"; - //when - ESTimeBasedEvent esTimeBasedEvent = ESTimeBasedEvent.createEventFromJson(stringJson); - Map fields = esTimeBasedEvent.getFields(); - //then - assertEquals(esTimeBasedEvent.timestamp, "2000-05-01 20:00:00.000 z"); - assertEquals(fields.get("event_type"), "activation"); - } - -} \ No newline at end of file diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/datastructure/WrapperTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/datastructure/WrapperTest.java index 84465c7160..a62a410c0a 100644 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/datastructure/WrapperTest.java +++ b/common-app-api/src/test/java/org/openecomp/sdc/common/datastructure/WrapperTest.java @@ -26,7 +26,7 @@ import org.junit.Test; public class WrapperTest { private Wrapper createTestSubject() { - return new Wrapper("test"); + return new Wrapper(null); } diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/ecomplog/LoggerMetricTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/ecomplog/LoggerMetricTest.java deleted file mode 100644 index e82dd1be84..0000000000 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/ecomplog/LoggerMetricTest.java +++ /dev/null @@ -1,322 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.ecomplog; - -import org.junit.Test; - -import org.openecomp.sdc.common.log.elements.LoggerFactory; -import org.openecomp.sdc.common.log.elements.LoggerMetric; -import org.openecomp.sdc.common.log.enums.Severity; -import org.openecomp.sdc.common.log.wrappers.Logger; - - -public class LoggerMetricTest { - private static final Logger log = Logger.getLogger(LoggerMetricTest.class.getName()); - - private LoggerMetric createTestSubject() { - return LoggerFactory.getLogger(LoggerMetric.class,log); - } - - - @Test - public void testStartTimer() throws Exception { - LoggerMetric testSubject; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.startTimer(); - } - - - @Test - public void testSetKeyRequestId() throws Exception { - LoggerMetric testSubject; - String keyRequestId = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setKeyRequestId(keyRequestId); - } - - - @Test - public void testStopTimer() throws Exception { - LoggerMetric testSubject; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.stopTimer(); - } - - - @Test - public void testSetAutoServerFQDN() throws Exception { - LoggerMetric testSubject; - String serverFQDN = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setAutoServerFQDN(serverFQDN); - } - - - @Test - public void testSetAutoServerIPAddress() throws Exception { - LoggerMetric testSubject; - String serverIPAddress = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setAutoServerIPAddress(serverIPAddress); - } - - - @Test - public void testSetInstanceUUID() throws Exception { - LoggerMetric testSubject; - String instanceUUID = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setInstanceUUID(instanceUUID); - } - - - @Test - public void testSetOptProcessKey() throws Exception { - LoggerMetric testSubject; - String processKey = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setOptProcessKey(processKey); - } - - - @Test - public void testSetOptAlertSeverity() throws Exception { - LoggerMetric testSubject; - Severity alertSeverity = null; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setOptAlertSeverity(alertSeverity.OK); - } - - - @Test - public void testSetOptCustomField1() throws Exception { - LoggerMetric testSubject; - String customField1 = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setOptCustomField1(customField1); - } - - - @Test - public void testSetOptCustomField2() throws Exception { - LoggerMetric testSubject; - String customField2 = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setOptCustomField2(customField2); - } - - - @Test - public void testSetOptCustomField3() throws Exception { - LoggerMetric testSubject; - String customField3 = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setOptCustomField3(customField3); - } - - - @Test - public void testSetOptCustomField4() throws Exception { - LoggerMetric testSubject; - String customField4 = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setOptCustomField4(customField4); - } - - - @Test - public void testSetRemoteHost() throws Exception { - LoggerMetric testSubject; - String remoteHost = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setRemoteHost(remoteHost); - } - - - @Test - public void testSetServiceName() throws Exception { - LoggerMetric testSubject; - String serviceName = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setServiceName(serviceName); - } - - - @Test - public void testSetStatusCode() throws Exception { - LoggerMetric testSubject; - String statusCode = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setStatusCode(statusCode); - } - - - @Test - public void testSetPartnerName() throws Exception { - LoggerMetric testSubject; - String partnerName = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setPartnerName(partnerName); - } - - - @Test - public void testSetResponseCode() throws Exception { - LoggerMetric testSubject; - int responseCode = 0; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setResponseCode(responseCode); - } - - - @Test - public void testSetResponseDesc() throws Exception { - LoggerMetric testSubject; - String responseDesc = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setResponseDesc(responseDesc); - } - - - @Test - public void testSetOptServiceInstanceId() throws Exception { - LoggerMetric testSubject; - String serviceInstanceId = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setOptServiceInstanceId(serviceInstanceId); - } - - - @Test - public void testSetOptClassName() throws Exception { - LoggerMetric testSubject; - String className = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setOptClassName(className); - } - - - @Test - public void testSetTargetEntity() throws Exception { - LoggerMetric testSubject; - String targetEntity = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setTargetEntity(targetEntity); - } - - - @Test - public void testSetTargetServiceName() throws Exception { - LoggerMetric testSubject; - String targetServiceName = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setTargetServiceName(targetServiceName); - } - - - @Test - public void testSetTargetVirtualEntity() throws Exception { - LoggerMetric testSubject; - String targetVirtualEntity = ""; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.setTargetVirtualEntity(targetVirtualEntity); - } - - - @Test - public void testClear() throws Exception { - LoggerMetric testSubject; - LoggerMetric result; - - // default test - testSubject = createTestSubject(); - result = testSubject.clear(); - } -} diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutableTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutableTest.java index eccd251b99..2593a000f8 100644 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutableTest.java +++ b/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutableTest.java @@ -24,11 +24,11 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.sdc.security.SecurityUtil; import org.openecomp.sdc.common.http.config.BasicAuthorization; import org.openecomp.sdc.common.http.config.ClientCertificate; import org.openecomp.sdc.common.http.config.HttpClientConfig; import org.openecomp.sdc.common.http.config.Timeouts; -import org.openecomp.sdc.security.SecurityUtil; import java.util.Collections; import java.util.Map; diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpClientFactoryTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpClientFactoryTest.java index ddfed06a66..c39bef0f4a 100644 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpClientFactoryTest.java +++ b/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpClientFactoryTest.java @@ -25,11 +25,11 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.sdc.security.SecurityUtil; import org.openecomp.sdc.common.http.config.BasicAuthorization; import org.openecomp.sdc.common.http.config.ClientCertificate; import org.openecomp.sdc.common.http.config.HttpClientConfig; import org.openecomp.sdc.common.http.config.Timeouts; -import org.openecomp.sdc.security.SecurityUtil; import java.util.Collections; import java.util.Map; diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactoryTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactoryTest.java index eb3263759e..2813d57cd0 100644 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactoryTest.java +++ b/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactoryTest.java @@ -22,8 +22,8 @@ package org.openecomp.sdc.common.http.client.api; import org.apache.http.conn.HttpClientConnectionManager; import org.junit.Test; +import org.onap.sdc.security.SecurityUtil; import org.openecomp.sdc.common.http.config.ClientCertificate; -import org.openecomp.sdc.security.SecurityUtil; import static org.junit.Assert.assertNotNull; diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandlerTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandlerTest.java deleted file mode 100644 index 155ea4fb0b..0000000000 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandlerTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - -import org.junit.Before; -import org.junit.Test; -import org.slf4j.MDC; - -import static org.junit.Assert.*; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.*; - -public class LogFieldsMdcHandlerTest { - - private LogFieldsMdcHandler ecompMdcWrapper; - - @Before - public void init(){ - ecompMdcWrapper = new LogFieldsMdcHandler(); - ecompMdcWrapper.clear(); - MDC.clear(); - } - - @Test - public void isMDCParamEmpty_shouldReturnTrue_onNonNullValueInMDC(){ - MDC.put("Key","value1"); - assertFalse(ecompMdcWrapper.isMDCParamEmpty("Key")); - } - @Test - public void isMDCParamEmpty_shouldReturnFalse_onEmptyStringInMDC(){ - MDC.put("Key",""); - assertTrue(ecompMdcWrapper.isMDCParamEmpty("Key")); - } - - @Test - public void isMDCParamEmpty_shouldReturnFalse_onNullValueInMDC(){ - MDC.put("Key",null); - assertTrue(ecompMdcWrapper.isMDCParamEmpty("Key")); - } - - @Test - public void startTimer_shouldFilecompMdcWrappereginTimestampField(){ - ecompMdcWrapper.startMetricTimer(); - assertFalse(ecompMdcWrapper.isMDCParamEmpty(MDC_METRIC_BEGIN_TIMESTAMP)); - } - - @Test - public void stopTimer_shouldFillEndTimestampField_ifStartTimerWasCalledPreviously(){ - ecompMdcWrapper.startAuditTimer(); - ecompMdcWrapper.stopAuditTimer(); - assertFalse(ecompMdcWrapper.isMDCParamEmpty(MDC_END_TIMESTAMP)); - } - - @Test - public void clear_shouldRemoveAllMandatoryAndOptionalFields_And_OnlyThem(){ - ecompMdcWrapper.setClassName("class1"); - ecompMdcWrapper.setPartnerName("partner1"); - ecompMdcWrapper.setOptCustomField1("of1"); - ecompMdcWrapper.clear(); - assertNull(MDC.get(MDC_CLASS_NAME)); - assertNull(MDC.get(MDC_PARTNER_NAME)); - assertNull(MDC.get(MDC_OPT_FIELD1)); - } - - @Test - public void clear_shouldNotThrowAnException_WhenNoFieldWasAssignedAsMandatoryOrOptional(){ - ecompMdcWrapper.setClassName("class1"); - ecompMdcWrapper.setPartnerName("partner1"); - ecompMdcWrapper.setOptCustomField1("of1"); - Exception exp = null; - try { - ecompMdcWrapper.clear(); - } - catch (Exception e) - { - exp =e; - } - assertNull(exp); - } - -} - diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAsdcUtilTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAsdcUtilTest.java deleted file mode 100644 index 693a084b25..0000000000 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAsdcUtilTest.java +++ /dev/null @@ -1,190 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.openecomp.sdc.common.log.enums.Severity; -import org.openecomp.sdc.common.log.wrappers.LoggerSdcAudit; -import org.openecomp.sdc.common.log.wrappers.LoggerSdcUtilBase; - -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.core.UriInfo; -import java.net.URI; -import java.net.URISyntaxException; - -import static java.net.HttpURLConnection.*; -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; - -/** - * Created by dd4296 on 12/19/2017. - * - * test get partner name - */ -@RunWith(MockitoJUnitRunner.class) -public class LoggerAsdcUtilTest { - - private final String chromeUserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"; - private final String firefoxUserAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.13) Gecko/20080313 Firefox"; - private final String explorerUserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0)"; - - private final String testUserId = "ml007"; - private final String urlWithUserName = "/api/v1/user/" + testUserId; - - class SdcEelfAuditTest extends LoggerSdcAudit { - - SdcEelfAuditTest(Class clazz) { - super(clazz); - } - - public String getPartnerName(String userAgent, String userID, String url) { - return super.getPartnerName(userAgent, userID, url); - } - } - - @Mock - private ContainerRequestContext requestContext; - @Mock - UriInfo uriInfo; - - private SdcEelfAuditTest asdcEelfAudit; - - @Before - public void Init () throws URISyntaxException { - asdcEelfAudit = new SdcEelfAuditTest(LoggerAsdcUtilTest.class); - when(requestContext.getHeaderString(anyString())).thenReturn("ab2222"); - when(requestContext.getUriInfo()).thenReturn(uriInfo); - URI uri = new URI("http:/abc.com/getId"); - when(uriInfo.getRequestUri()).thenReturn(uri); - when(uriInfo.getBaseUri()).thenReturn(uri); - - } - - @Test - public void extract_user_id_from_userAgentTest() { - - String userIdChrome = asdcEelfAudit.getPartnerName(chromeUserAgent, "", ""); - assertEquals(userIdChrome.toLowerCase(), "chrome_FE".toLowerCase()); - - String userIdFireFox = asdcEelfAudit.getPartnerName(firefoxUserAgent, "", ""); - assertEquals(userIdFireFox.toLowerCase(), "firefox_FE".toLowerCase()); - - String userIdIE = asdcEelfAudit.getPartnerName(explorerUserAgent, "", ""); - assertEquals(userIdIE.toLowerCase(), "explorer_FE".toLowerCase()); - } - - @Test - public void extract_user_id_from_urlTest() { - - String userId = asdcEelfAudit.getPartnerName("", "", urlWithUserName); - assertEquals(testUserId, userId); - } - - @Test - public void extract_user_id_from_paramTest() { - - String userId = asdcEelfAudit.getPartnerName("", testUserId, ""); - assertEquals(userId, testUserId); - } - - @Test - public void extract_user_id_priorityTest() { - - String userId = asdcEelfAudit.getPartnerName(chromeUserAgent, testUserId, urlWithUserName); - assertEquals(userId, testUserId); - - String userIdUrl = asdcEelfAudit.getPartnerName(chromeUserAgent, "", urlWithUserName); - assertEquals(userIdUrl, testUserId); - - String userIdUserAgent = asdcEelfAudit.getPartnerName(chromeUserAgent, "", ""); - assertEquals(userIdUserAgent.toLowerCase(), "chrome_FE".toLowerCase()); - } - - @Test - public void check_http_error_convert_to_eelf_code() { - class LoggerSdcUtilBaseTest extends LoggerSdcUtilBase { - public EcompLoggerErrorCode convertHttpCodeToErrorCode(int httpResponseCode) { - return super.convertHttpCodeToErrorCode(httpResponseCode); - } - } - - LoggerSdcUtilBaseTest utilBase = new LoggerSdcUtilBaseTest(); - - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_BAD_REQUEST), EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR); - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_UNAUTHORIZED), EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR); - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_NOT_FOUND), EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR); - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_CLIENT_TIMEOUT), EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR); - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_GONE), EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR); - - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_PAYMENT_REQUIRED), EcompLoggerErrorCode.PERMISSION_ERROR); - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_FORBIDDEN), EcompLoggerErrorCode.PERMISSION_ERROR); - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_BAD_METHOD), EcompLoggerErrorCode.PERMISSION_ERROR); - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_PROXY_AUTH), EcompLoggerErrorCode.PERMISSION_ERROR); - - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_NOT_ACCEPTABLE), EcompLoggerErrorCode.DATA_ERROR); - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_LENGTH_REQUIRED), EcompLoggerErrorCode.DATA_ERROR); - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_PRECON_FAILED), EcompLoggerErrorCode.DATA_ERROR); - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_REQ_TOO_LONG), EcompLoggerErrorCode.DATA_ERROR); - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_ENTITY_TOO_LARGE), EcompLoggerErrorCode.DATA_ERROR); - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_UNSUPPORTED_TYPE), EcompLoggerErrorCode.DATA_ERROR); - - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_CONFLICT), EcompLoggerErrorCode.SCHEMA_ERROR); - - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_OK), EcompLoggerErrorCode.SUCCESS); - - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_INTERNAL_ERROR), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_NOT_IMPLEMENTED), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_BAD_GATEWAY), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_UNAVAILABLE), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_GATEWAY_TIMEOUT), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); - Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_VERSION), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); - - } - - @Test - public void takenCareOf_shouldBeTrue_ifStartedLogWasCalled(){ - asdcEelfAudit.startLog(requestContext); - assertTrue(asdcEelfAudit.isFlowBeingTakenCare()); - } - - @Test - public void takenCareOf_shouldBeFalse_ifStartedLogWasNoCalled(){ - assertFalse(asdcEelfAudit.isFlowBeingTakenCare()); - } - - @Test - public void takenCareOf_shouldBeFalse_ifStartedLogWasCalleAndLogWasCalledToo(){ - asdcEelfAudit.startLog(requestContext); - - asdcEelfAudit.log(null,null,null, LogLevel.INFO, Severity.OK, "message"); - assertFalse(asdcEelfAudit.isFlowBeingTakenCare()); - } - -} diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAuditTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAuditTest.java deleted file mode 100644 index 665fecec2c..0000000000 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAuditTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.openecomp.sdc.common.log.enums.Severity; -import org.openecomp.sdc.common.log.enums.StatusCode; -import org.slf4j.Logger; -import org.slf4j.MDC; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.UUID; - -import static org.openecomp.sdc.common.log.api.ILogConfiguration.*; -import static org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler.hostAddress; - -@RunWith(MockitoJUnitRunner.class) -public class LoggerAuditTest { - @Mock - private Logger logger; - - private LoggerAudit auditLog; - - @Before - public void init() { - auditLog = new LoggerAudit(LogFieldsMdcHandler.getInstance(), logger); - } - - @After - public void tearDown() { - MDC.clear(); - } - - @Test - public void whenNoAuditFieldsArePopulated_ShouldReturnAssertTrue_onMdcMap() { - auditLog.clear() - .log(LogLevel.INFO, "some error code"); - Assert.assertNotNull(MDC.get(MDC_SERVER_FQDN)); - Assert.assertNotNull(MDC.get(MDC_SERVER_IP_ADDRESS)); - } - - @Test - public void whenAllAuditFieldsArePopulated_ShouldReturnAssertTrue_onEachMACField() throws UnknownHostException { - - String uuid = UUID.randomUUID().toString(); - String hostName = InetAddress.getByName(hostAddress).getCanonicalHostName(); - String hostAddress = InetAddress.getLocalHost().getHostAddress(); - - auditLog.clear() - .startTimer() - .stopTimer() - .setKeyRequestId(uuid) - .setInstanceUUID(MDC_INSTANCE_UUID) - .setRemoteHost(MDC_REMOTE_HOST) - .setServiceName(MDC_SERVICE_NAME) - .setResponseCode(EcompLoggerErrorCode.DATA_ERROR) - .setStatusCode("201") - .setResponseDesc(MDC_RESPONSE_DESC) - .setPartnerName(MDC_PARTNER_NAME) - - .setOptClassName(LoggerAuditTest.class.toString()) - .setOptAlertSeverity(Severity.CRITICAL) - .setOptProcessKey(MDC_PROCESS_KEY) - .setOptServiceInstanceId(MDC_SERVICE_INSTANCE_ID) - .log(LogLevel.DEBUG, ""); - - - Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_AUDIT_BEGIN_TIMESTAMP)); - Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_END_TIMESTAMP)); - Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_ELAPSED_TIME)); - - Assert.assertEquals(MDC.get(MDC_SERVER_IP_ADDRESS), hostAddress); - Assert.assertEquals(MDC.get(MDC_SERVER_FQDN), hostName); - Assert.assertEquals(MDC.get(MDC_REMOTE_HOST), MDC_REMOTE_HOST); - Assert.assertEquals(MDC.get(MDC_STATUS_CODE), StatusCode.COMPLETE.getStatusCodeEnum()); - - Assert.assertEquals(MDC.get(MDC_KEY_REQUEST_ID), uuid); - Assert.assertEquals(MDC.get(MDC_SERVICE_NAME), MDC_SERVICE_NAME); - Assert.assertEquals(MDC.get(MDC_PARTNER_NAME), MDC_PARTNER_NAME); - Assert.assertEquals(MDC.get(MDC_RESPONSE_CODE), String.valueOf(EcompLoggerErrorCode.DATA_ERROR.getErrorCode())); - Assert.assertEquals(MDC.get(MDC_RESPONSE_DESC), MDC_RESPONSE_DESC); - Assert.assertEquals(MDC.get(MDC_INSTANCE_UUID), MDC_INSTANCE_UUID); - Assert.assertEquals(MDC.get(MDC_CLASS_NAME), LoggerAuditTest.class.toString()); - - Assert.assertEquals(MDC.get(MDC_ALERT_SEVERITY), String.valueOf(Severity.CRITICAL.getSeverityType())); - Assert.assertEquals(MDC.get(MDC_PROCESS_KEY), MDC_PROCESS_KEY); - Assert.assertEquals(MDC.get(MDC_SERVICE_INSTANCE_ID), MDC_SERVICE_INSTANCE_ID); - } -} diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LoggerDebugTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LoggerDebugTest.java deleted file mode 100644 index 13f7804501..0000000000 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LoggerDebugTest.java +++ /dev/null @@ -1,109 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - -/** - * Created by dd4296 on 12/25/2017. - */ - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.openecomp.sdc.common.util.ThreadLocalsHolder; -import org.slf4j.Logger; -import org.slf4j.MDC; - -import java.net.UnknownHostException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.*; - -@RunWith(MockitoJUnitRunner.class) -public class LoggerDebugTest { - - @Mock - private Logger logger; - - private LoggerDebug debugLog; - - @Before - public void init() { - debugLog = new LoggerDebug(LogFieldsMdcHandler.getInstance(), logger); - ThreadLocalsHolder.setUuid(null); - MDC.clear(); - } - - @Test - public void whenNoFieldsIsPopulated_RequestedMdcFieldsAreEmpty() { - debugLog.clear() - .log(LogLevel.DEBUG, "some error code"); - assertNull(MDC.get(MDC_KEY_REQUEST_ID)); - } - - @Test - public void debugLogCheckValidationValidFieldsTest() { - debugLog.clear() - .startTimer() - .setKeyRequestId("uuid") - .log(LogLevel.DEBUG, "some error code"); - - Assert.assertEquals(MDC.get(MDC_KEY_REQUEST_ID), "uuid"); - } - - @Test - public void whenOnlyDebugUUIDFieldsIsPopulated_ShouldReturnAssertTrue_onUUIDFieldCheck() { - debugLog.clear() - .setKeyRequestId("uuid") - .log(LogLevel.DEBUG, "some error code"); - - Assert.assertEquals(MDC.get(MDC_KEY_REQUEST_ID), "uuid"); - } - - @Test - public void whenAllDebugFieldsArePopulated_ShouldReturnAssertTrue_onEachMACFieldCheck() throws UnknownHostException { - debugLog.clear() - .startTimer() - .setKeyRequestId(MDC_KEY_REQUEST_ID) - .log(LogLevel.DEBUG, "some message"); - - Assert.assertTrue(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_END_TIMESTAMP)); - Assert.assertTrue(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_ELAPSED_TIME)); - Assert.assertTrue(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_STATUS_CODE)); - } - - - @Test - public void validateMandatoryFields(){ - assertEquals(MDC_KEY_REQUEST_ID, debugLog.checkMandatoryFieldsExistInMDC().trim()); - } - - @Test - public void validateMandatoryFieldsWhenFieldIsSet(){ - debugLog.clear() - .setKeyRequestId("1234"); - assertEquals("", debugLog.checkMandatoryFieldsExistInMDC()); - } -} diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LoggerErrorTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LoggerErrorTest.java deleted file mode 100644 index 99417f74bf..0000000000 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LoggerErrorTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.openecomp.sdc.common.config.EcompErrorCode; -import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.openecomp.sdc.common.util.ThreadLocalsHolder; -import org.slf4j.Logger; -import org.slf4j.MDC; - -import static org.junit.Assert.assertEquals; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.*; - -@RunWith(MockitoJUnitRunner.class) -public class LoggerErrorTest { - private LoggerError errorLog; - - @Mock - private Logger logger; - @Before - public void init() { - errorLog = LoggerFactory.getMdcLogger(LoggerError.class, logger); - MDC.clear(); - } - - @Test - public void allFieldsArePresentTest() { - ThreadLocalsHolder.setUuid("uuid"); - errorLog.log(LogLevel.ERROR, EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR, "service", "entity", "server error"); - - Assert.assertEquals(MDC.get(MDC_ERROR_CODE), String.valueOf(EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR.getErrorCode())); - Assert.assertEquals("uuid", MDC.get(MDC_KEY_REQUEST_ID)); - Assert.assertEquals("entity", MDC.get(MDC_TARGET_ENTITY)); - Assert.assertEquals("service", MDC.get(MDC_SERVICE_NAME)); - } - - @Test - public void missingFieldsTest() { - errorLog.clear() - .log(LogLevel.ERROR,"some message"); - } - - @Test - public void convertEcompErrorForLogging_correctName() { - assertEquals(EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR, EcompLoggerErrorCode.getByValue(EcompErrorCode.E_210.name())); - } - - @Test - public void convertEcompErrorForLogging_correctName_2() { - assertEquals(EcompLoggerErrorCode.DATA_ERROR, EcompLoggerErrorCode.getByValue(EcompErrorCode.E_399.name())); - } - - @Test - public void convertEcompErrorForLogging_NotConvertable() { - assertEquals(EcompLoggerErrorCode.UNKNOWN_ERROR, EcompLoggerErrorCode.getByValue("ABC")); - } - - @Test - public void convertEcompErrorForLogging_NotConvertable_2() { - assertEquals(EcompLoggerErrorCode.UNKNOWN_ERROR, EcompLoggerErrorCode.getByValue("E_ABC")); - } - - @Test - public void convertEcompErrorForLogging_Success() { - assertEquals(EcompLoggerErrorCode.SUCCESS, EcompLoggerErrorCode.getByValue("E_0")); - } -} diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LoggerMetricTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LoggerMetricTest.java deleted file mode 100644 index 7d20d216ae..0000000000 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/log/elements/LoggerMetricTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.openecomp.sdc.common.log.enums.Severity; -import org.openecomp.sdc.common.util.ThreadLocalsHolder; -import org.slf4j.Logger; -import org.slf4j.MDC; - -import javax.ws.rs.core.Response; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.UUID; - -import static org.openecomp.sdc.common.log.api.ILogConfiguration.*; -import static org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler.hostAddress; - -/** - * Created by dd4296 on 12/31/2017. - */ -@RunWith(MockitoJUnitRunner.class) -public class LoggerMetricTest { - @Mock - private Logger logger; - - @Mock - Response.StatusType statusType; - - private LoggerMetric metricLog; - - @Before - public void init() { - metricLog = new LoggerMetric(LogFieldsMdcHandler.getInstance(), logger); - } - - @After - public void tearDown() { - MDC.clear(); - ThreadLocalsHolder.setUuid(null); - } - - @Test - public void whenNoMetricFieldsArePopulated_ShouldReturnassertEquals_onMdcMap() { - metricLog.clear() - .log(LogLevel.DEBUG, "some error code"); - Assert.assertNotNull(MDC.get(MDC_SERVER_FQDN)); - Assert.assertNotNull(MDC.get(MDC_SERVER_IP_ADDRESS)); - } - - @Test - public void whenAllMetricFieldsArePopulated_ShouldReturnassertEquals_onEachMACField() throws UnknownHostException { - String uuid = UUID.randomUUID().toString(); - ThreadLocalsHolder.setUuid(uuid); - - String hostName = InetAddress.getByName(hostAddress).getCanonicalHostName(); - String hostAddress = InetAddress.getLocalHost().getHostAddress(); - - metricLog.clear() - .startTimer() - .stopTimer() - .setInstanceUUID(MDC_INSTANCE_UUID) - .setRemoteHost(MDC_REMOTE_HOST) - .setServiceName(MDC_SERVICE_NAME) - .setResponseCode(500) - .setStatusCode("201") - .setResponseDesc(MDC_RESPONSE_DESC) - .setPartnerName(MDC_PARTNER_NAME) - - .setOptClassName(LoggerMetricTest.class.toString()) - .setOptAlertSeverity(Severity.CRITICAL) - .setOptProcessKey(MDC_PROCESS_KEY) - .setOptServiceInstanceId(MDC_SERVICE_INSTANCE_ID) - - .setTargetEntity(MDC_TARGET_ENTITY) - .setTargetServiceName(MDC_TARGET_SERVICE_NAME) - .setTargetVirtualEntity(MDC_TARGET_VIRTUAL_ENTITY) - - .log(LogLevel.DEBUG, ""); - - - Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_METRIC_BEGIN_TIMESTAMP)); - Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_END_TIMESTAMP)); - Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_ELAPSED_TIME)); - - Assert.assertEquals(MDC.get(MDC_SERVER_IP_ADDRESS),hostAddress); - Assert.assertEquals(MDC.get(MDC_SERVER_FQDN), hostName); - Assert.assertEquals(MDC.get(MDC_REMOTE_HOST), MDC_REMOTE_HOST); - Assert.assertEquals(MDC.get(MDC_STATUS_CODE) ,"201"); - - Assert.assertEquals(MDC.get(MDC_KEY_REQUEST_ID), uuid); - Assert.assertEquals(MDC.get(MDC_SERVICE_NAME) ,MDC_SERVICE_NAME); - Assert.assertEquals(MDC.get(MDC_PARTNER_NAME) ,MDC_PARTNER_NAME); - Assert.assertEquals(MDC.get(MDC_RESPONSE_CODE) ,"500"); - Assert.assertEquals(MDC.get(MDC_RESPONSE_DESC) ,MDC_RESPONSE_DESC); - Assert.assertEquals(MDC.get(MDC_INSTANCE_UUID) ,MDC_INSTANCE_UUID); - Assert.assertEquals(MDC.get(MDC_CLASS_NAME) ,LoggerMetricTest.class.toString()); - - Assert.assertEquals(MDC.get(MDC_ALERT_SEVERITY) ,String.valueOf(Severity.CRITICAL.getSeverityType())); - Assert.assertEquals(MDC.get(MDC_PROCESS_KEY) ,MDC_PROCESS_KEY); - Assert.assertEquals(MDC.get(MDC_SERVICE_INSTANCE_ID) ,MDC_SERVICE_INSTANCE_ID); - - Assert.assertEquals(MDC.get(MDC_TARGET_ENTITY) ,MDC_TARGET_ENTITY); - Assert.assertEquals(MDC.get(MDC_TARGET_SERVICE_NAME) ,MDC_TARGET_SERVICE_NAME); - Assert.assertEquals(MDC.get(MDC_TARGET_VIRTUAL_ENTITY) ,MDC_TARGET_VIRTUAL_ENTITY); - } -} diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/log/wrappers/LoggerTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/log/wrappers/LoggerTest.java deleted file mode 100644 index 858d777efd..0000000000 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/log/wrappers/LoggerTest.java +++ /dev/null @@ -1,281 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.wrappers; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.openecomp.sdc.common.log.api.ILogConfiguration; -import org.openecomp.sdc.common.log.elements.LoggerError; -import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.openecomp.sdc.common.log.enums.Severity; -import org.openecomp.sdc.common.util.ThreadLocalsHolder; -import org.slf4j.MDC; -import org.slf4j.Marker; - -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; -import java.net.URI; -import java.net.URISyntaxException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.contains; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.*; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.*; - -@RunWith(MockitoJUnitRunner.class) -public class LoggerTest { - - private final static String targetEntity = "DCEA"; - private final static String serviceName = "testService"; - private final static String message = "Logger message"; - private final static String exceptionMsg= "Exception testing"; - private final static String missingFieldsMessageFragment = "mandatory parameters for ECOMP logging"; - - @Mock - private org.slf4j.Logger logger; - @Mock - private ContainerRequestContext requestContext; - @Mock - private UriInfo uriInfo; - @Mock - private Response.StatusType statusType; - - @InjectMocks - private Logger commonLogger; - - @Captor - private ArgumentCaptor captor; - - @Before - public void setUp() { - MDC.clear(); - } - - @Test - public void validateErrorLogWhenErrorSettingsProvided() { - when(logger.isErrorEnabled()).thenReturn(true); - commonLogger.error(EcompLoggerErrorCode.PERMISSION_ERROR, serviceName, targetEntity, message); - - verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); - assertEquals(message, captor.getValue()); - assertEquals(String.valueOf(EcompLoggerErrorCode.PERMISSION_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE)); - assertEquals(LogLevel.ERROR.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY)); - assertEquals(targetEntity, MDC.get(ILogConfiguration.MDC_TARGET_ENTITY)); - assertEquals(serviceName, MDC.get(ILogConfiguration.MDC_SERVICE_NAME)); - } - - @Test - public void validateWarnMessageIsLoggedWhenAllErrorSettingsProvided() { - when(logger.isErrorEnabled()).thenReturn(true); - commonLogger.error(EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR, serviceName, targetEntity, message); - - verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); - assertEquals(message, captor.getValue()); - assertEquals(String.valueOf(EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE)); - assertEquals(LogLevel.ERROR.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY)); - assertEquals(targetEntity, MDC.get(ILogConfiguration.MDC_TARGET_ENTITY)); - assertEquals(serviceName, MDC.get(ILogConfiguration.MDC_SERVICE_NAME)); - } - - @Test - public void validateFatalMessageIsLoggedWhenAllErrorSettingsProvided() { - when(logger.isErrorEnabled()).thenReturn(true); - commonLogger.fatal(EcompLoggerErrorCode.PERMISSION_ERROR, serviceName, targetEntity, message); - - verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); - assertEquals(message, captor.getValue()); - assertEquals(String.valueOf(EcompLoggerErrorCode.PERMISSION_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE)); - assertEquals(LogLevel.FATAL.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY)); - assertEquals(targetEntity, MDC.get(ILogConfiguration.MDC_TARGET_ENTITY)); - assertEquals(serviceName, MDC.get(ILogConfiguration.MDC_SERVICE_NAME)); - } - - @Test - public void validateErrorMessageIsNotLoggedWhenErrorLevelIsDisabledEvenIfErrorSettingsProvided() { - commonLogger.error(EcompLoggerErrorCode.PERMISSION_ERROR, serviceName, targetEntity, message); - verify(logger, never()).error(any(Marker.class), any(String.class)); - } - - @Test - public void validateErrorLogWhenErrorSettingsProvidedPartially() { - when(logger.isErrorEnabled()).thenReturn(true); - commonLogger.error(message); - - verify(logger).error(any(Marker.class), eq(message), any(Object[].class)); - assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE)); - assertEquals(LogLevel.ERROR.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY)); - assertNull(MDC.get(ILogConfiguration.MDC_TARGET_ENTITY)); - assertEquals(LoggerError.defaultServiceName, MDC.get(ILogConfiguration.MDC_SERVICE_NAME)); - } - - @Test - public void errorMessageIsNotLoggedWhenErrorLevelIsDisabled() { - commonLogger.error(message); - verify(logger, times(0)).error(any(Marker.class), anyString()); - } - - @Test - public void traceMessageWithExceptionIsNotLoggedWhenTraceLevelIsDisabled() { - commonLogger.trace(message, new UnsupportedOperationException()); - verify(logger, times(0)).trace(any(Marker.class), anyString()); - } - - @Test - public void verifyInfoMessage() { - when(logger.isInfoEnabled()).thenReturn(true); - commonLogger.info("Text"); - assertEquals(LogLevel.INFO.name(), MDC.get(MDC_ERROR_CATEGORY)); - assertEquals(String.valueOf(EcompLoggerErrorCode.SUCCESS.getErrorCode()), MDC.get(MDC_ERROR_CODE)); - assertEquals(LoggerError.defaultServiceName, MDC.get(ILogConfiguration.MDC_SERVICE_NAME)); - } - - @Test - public void verifyWarnMessage() { - when(logger.isWarnEnabled()).thenReturn(true); - commonLogger.warn("Text"); - assertEquals(LogLevel.WARN.name(), MDC.get(MDC_ERROR_CATEGORY)); - assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(MDC_ERROR_CODE)); - assertEquals(LoggerError.defaultServiceName, MDC.get(ILogConfiguration.MDC_SERVICE_NAME)); - } - - @Test - public void validateErrorLogWithExceptionWhenErrorSettingsProvidedPartially() { - ThreadLocalsHolder.setUuid("uuid"); - final String logFieldsNotProvidedMsg = "mandatory parameters for ECOMP logging, missing fields: ServiceName PartnerName"; - when(logger.isWarnEnabled()).thenReturn(true); - commonLogger.warn(message, new NullPointerException(exceptionMsg)); - - //the expected warn message - verify(logger).warn(any(Marker.class), contains(message), any(Object[].class)); - assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE)); - assertEquals(LogLevel.WARN.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY)); - assertEquals("uuid", MDC.get(ILogConfiguration.MDC_KEY_REQUEST_ID)); - assertNull(MDC.get(ILogConfiguration.MDC_TARGET_ENTITY)); - assertEquals(LoggerError.defaultServiceName, MDC.get(ILogConfiguration.MDC_SERVICE_NAME)); - } - - - @Test - public void validateDebugLogWithException() { - final String msg = "Debug message"; - ThreadLocalsHolder.setUuid("uuid"); - when(logger.isDebugEnabled()).thenReturn(true); - commonLogger.debug(msg, new RuntimeException()); - - verify(logger).debug(any(Marker.class), eq(msg), any(RuntimeException.class)); - } - - @Test - public void validateTraceLogWithExceptionAndPartialParamsAndDebugLevelDisabled() { - final String msg = "Debug message"; - when(logger.isTraceEnabled()).thenReturn(true); - commonLogger.trace(msg, new RuntimeException()); - - verify(logger).trace(any(Marker.class), eq(msg), any(RuntimeException.class)); - } - - @Test - public void warnMessageWithParameterIsNotLoggedIfWarnLevelIsDisabled() { - commonLogger.warn("msg", "param"); - verify(logger, times(0)).warn(any(Marker.class), - anyString(), any(Object.class)); - } - - @Test - public void verifyMdcValuesAreStoredWhenAuditAndErrorLoggersAreInvokedSequentially() throws URISyntaxException { - final String uuid = "12345"; - final String message = "message"; - when(requestContext.getHeaderString(anyString())).thenReturn("ab2222"); - when(requestContext.getUriInfo()).thenReturn(uriInfo); - when(logger.isErrorEnabled()).thenReturn(true); - - URI uri = new URI("http:/abc.com/getId"); - when(uriInfo.getRequestUri()).thenReturn(uri); - when(uriInfo.getBaseUri()).thenReturn(uri); - when(statusType.getStatusCode()).thenReturn(200); - when(statusType.getReasonPhrase()).thenReturn("OK"); - LoggerSdcAudit audit = new LoggerSdcAudit(this.getClass()); - ThreadLocalsHolder.setUuid(uuid); - audit.startLog(requestContext); - audit.log("abc.log.com", requestContext, statusType, LogLevel.INFO, Severity.OK, message); - - commonLogger.error(message); - verify(logger).error(any(Marker.class), eq(message), any(Object[].class)); - assertEquals(uuid, MDC.get(MDC_KEY_REQUEST_ID)); - assertEquals("/", MDC.get(MDC_SERVICE_NAME)); - assertEquals(LogLevel.ERROR.name(), MDC.get(MDC_ERROR_CATEGORY)); - assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(MDC_ERROR_CODE)); - } - - @Test - public void verifyLoggerDoesNothingWhenTheLevelIsNotSet() { - if (commonLogger.isDebugEnabled()) { - commonLogger.debug("text"); - } - verify(logger, times(0)).debug(any(Marker.class), anyString(), eq((Object[])null)); - } - - @Test - public void verifyLoggerTraceMethodIsCalledWhenTheLevelIsSet() { - ThreadLocalsHolder.setUuid("1234"); - when(logger.isTraceEnabled()).thenReturn(true); - if (commonLogger.isTraceEnabled()) { - commonLogger.trace("text"); - } - verify(logger, times(1)).trace(any(Marker.class), anyString(), eq((Object[])null)); - } - - - @Test - public void verifyMdcValuesAreStoredWhenTraceLoggerIsInvokedAfterAuditStart() throws URISyntaxException { - final String uuid = "12345"; - final String message = "message"; - when(requestContext.getHeaderString(anyString())).thenReturn("ab2222"); - when(requestContext.getUriInfo()).thenReturn(uriInfo); - when(logger.isTraceEnabled()).thenReturn(true); - - URI uri = new URI("http:/abc.com/getId"); - when(uriInfo.getRequestUri()).thenReturn(uri); - when(uriInfo.getBaseUri()).thenReturn(uri); - LoggerSdcAudit audit = new LoggerSdcAudit(this.getClass()); - ThreadLocalsHolder.setUuid(uuid); - audit.startLog(requestContext); - - commonLogger.trace(message); - verify(logger).trace(any(Marker.class), captor.capture(), eq((Object[])null)); - assertEquals(message, captor.getValue()); - assertEquals(uuid, MDC.get(MDC_KEY_REQUEST_ID)); - } - - -} diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/test/CommonUtilsTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/test/CommonUtilsTest.java index fadb9d47aa..73d8c116e2 100644 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/test/CommonUtilsTest.java +++ b/common-app-api/src/test/java/org/openecomp/sdc/common/test/CommonUtilsTest.java @@ -83,16 +83,6 @@ public class CommonUtilsTest { } - @Test - public void testFloatParsing() { - assertTrue(ValidationUtils.isFloatNumber("15555.45")); - assertTrue(ValidationUtils.isFloatNumber("0.5")); - assertFalse(ValidationUtils.isFloatNumber("15555")); - assertFalse(ValidationUtils.isFloatNumber("1")); - assertFalse(ValidationUtils.isFloatNumber("jk532")); - assertFalse(ValidationUtils.isFloatNumber("12..6")); - - } @Test public void testValidateIconLength() { @@ -379,31 +369,6 @@ public class CommonUtilsTest { } - @Test - public void validateConsumerNameTest() { - assertTrue(ValidationUtils.validateConsumerName("ab037cd")); - assertFalse(ValidationUtils.validateConsumerName(" ")); - assertTrue(ValidationUtils.validateConsumerName("_dD.d9")); - assertTrue(ValidationUtils.validateConsumerName("_dd.G9-")); - assertFalse(ValidationUtils.validateConsumerName(".dA.d9-")); - assertFalse(ValidationUtils.validateConsumerName("-d")); - assertFalse(ValidationUtils.validateConsumerName("d?")); - assertTrue(ValidationUtils.validateConsumerName("9")); - } - - @Test - public void validateConsumerPassSaltTest() { - assertTrue(ValidationUtils.validateConsumerPassSalt("ad35fg2")); - assertTrue(ValidationUtils.validateConsumerPassSalt("12s")); - assertTrue(ValidationUtils.validateConsumerPassSalt("9")); - assertFalse(ValidationUtils.validateConsumerPassSalt("dA.d9-")); - assertFalse(ValidationUtils.validateConsumerPassSalt("dASQe")); - assertFalse(ValidationUtils.validateConsumerPassSalt("_d")); - assertFalse(ValidationUtils.validateConsumerPassSalt("?")); - assertFalse(ValidationUtils.validateConsumerPassSalt("")); - assertFalse(ValidationUtils.validateConsumerPassSalt(" ")); - } - @Test public void validateCategoryNameFormatTest() { assertTrue(ValidationUtils.validateCategoryDisplayNameFormat("Net ele-2_3#456&+.'=:@@@@@#####")); diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/util/HealthCheckUtilTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/util/HealthCheckUtilTest.java index 3fc025eb22..d51f8c878b 100644 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/util/HealthCheckUtilTest.java +++ b/common-app-api/src/test/java/org/openecomp/sdc/common/util/HealthCheckUtilTest.java @@ -76,10 +76,9 @@ public class HealthCheckUtilTest { @Test public void validateGetAggregateDescriptionReturnsProperDescription() { - final String parentDescription = ""; when(healthCheckInfo.getHealthCheckStatus()).thenReturn(HealthCheckInfo.HealthCheckStatus.DOWN); - final String result = healthCheckUtil.getAggregateDescription(healthCheckInfos, parentDescription); + final String result = healthCheckUtil.getAggregateDescription(healthCheckInfos ); assertTrue(result.contains(testComponent)); assertTrue(result.contains("Down")); diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/util/ValidationUtilsTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/util/ValidationUtilsTest.java index e9f607b976..467f1cf545 100644 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/util/ValidationUtilsTest.java +++ b/common-app-api/src/test/java/org/openecomp/sdc/common/util/ValidationUtilsTest.java @@ -19,6 +19,7 @@ * ============LICENSE_END========================================================= */ + package org.openecomp.sdc.common.util; import com.google.common.collect.Lists; @@ -526,7 +527,7 @@ public class ValidationUtilsTest { @Test public void checkValidateStringNotEmptyReturnsFalseIfStringIsNotEmpty() { - final String testString = "test"; + final String testString = "test"; boolean result = ValidationUtils.validateStringNotEmpty(testString); @@ -802,10 +803,10 @@ public class ValidationUtilsTest { } @Test - public void validateIsUTF8StrReturnsFalseIfGivenStringContainsUtf8Character() { - final String testString = "test×§String"; + public void validateIsUTF8StrReturnsFalseIfGivenStringContainsUtf8Character(){ +final String testString="test×§String"; - boolean result = ValidationUtils.isUTF8Str(testString); + boolean result=ValidationUtils.isUTF8Str(testString); assertFalse(result); } @@ -892,10 +893,10 @@ public class ValidationUtilsTest { } @Test - public void checkValidateArtifactLabelReturnsFalseIfLabelIsNotValid() { - final String testArtifactDisplayName = "test=notValid=Label"; + public void checkValidateArtifactLabelReturnsFalseIfLabelIsNotValid(){ +final String testArtifactDisplayName="test=notValid=Label"; - boolean result = ValidationUtils.validateArtifactLabel(testArtifactDisplayName); + boolean result=ValidationUtils.validateArtifactLabel(testArtifactDisplayName); assertFalse(result); } @@ -910,13 +911,13 @@ public class ValidationUtilsTest { } @Test - public void checkValidateConsumerNameReturnsFalseIfLabelIsNotValid() { - final String testConsumerName = "test=notValid=ConsumerName"; + public void checkValidateConsumerNameReturnsFalseIfLabelIsNotValid(){ +final String testConsumerName="test=notValid=ConsumerName"; - boolean result = ValidationUtils.validateConsumerName(testConsumerName); + boolean result=ValidationUtils.validateConsumerName(testConsumerName); assertFalse(result); - } + } @Test public void checkValidateConsumerPassSaltReturnsTrueIfLabelIsValid() { diff --git a/common-app-api/src/test/java/org/openecomp/sdc/exception/AbstractSdncExceptionTest.java b/common-app-api/src/test/java/org/openecomp/sdc/exception/AbstractSdncExceptionTest.java new file mode 100644 index 0000000000..7b2dd19a68 --- /dev/null +++ b/common-app-api/src/test/java/org/openecomp/sdc/exception/AbstractSdncExceptionTest.java @@ -0,0 +1,53 @@ +package org.openecomp.sdc.exception; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.api.ILogConfiguration; +import org.slf4j.MDC; + +public class AbstractSdncExceptionTest { + @Before + public void clearMdcTable(){ + MDC.clear(); + } + + + @Test + public void testServiceExceptionEcompRequestIdNull() { + String[] variables = {"1234","Test_VF"}; + ServiceException serviceException = new ServiceException("SVC4628", "Error: The VSP with UUID %1 was already imported for VF %2. Please select another or update the existing VF.", variables); + String requestId=serviceException.getEcompRequestId(); + Assert.assertNull(requestId); + } + + @Test + public void testServiceExceptionEcompRequestIdNotNull() { + String[] variables = {"1234","Test_VF"}; + String expectedRequestId="b819266d-3b92-4e07-aec4-cb7f0d4010a4"; + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID,expectedRequestId); + ServiceException serviceException = new ServiceException("SVC4628", "Error: The VSP with UUID %1 was already imported for VF %2. Please select another or update the existing VF.", variables); + String requestId=serviceException.getEcompRequestId(); + Assert.assertEquals(requestId,expectedRequestId); + } + + + @Test + public void testPolicyExceptionEcompRequestIdfieldNull() { + String[] variables = {"1234","Test_VF"}; + PolicyException policyexception = new PolicyException("SVC4628", "Error: The VSP with UUID %1 was already imported for VF %2. Please select another or update the existing VF.", variables); + String requestId=policyexception.getEcompRequestId(); + Assert.assertNull(requestId); + } + + @Test + public void testPolicyExceptionEcompRequestIdNotNull() { + String[] variables = {"1234","Test_VF"}; + String expectedRequestId="b819266d-3b92-4e07-aec4-cb7f0d4010a4"; + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID,expectedRequestId); + PolicyException policyexception = new PolicyException("SVC4628", "Error: The VSP with UUID %1 was already imported for VF %2. Please select another or update the existing VF.", variables); + String requestId=policyexception.getEcompRequestId(); + Assert.assertEquals(requestId,expectedRequestId); + } +} diff --git a/common-app-api/src/test/resources/config/common/configuration.yaml b/common-app-api/src/test/resources/config/common/configuration.yaml index 24c7936d7f..eba8ee1c62 100644 --- a/common-app-api/src/test/resources/config/common/configuration.yaml +++ b/common-app-api/src/test/resources/config/common/configuration.yaml @@ -33,7 +33,6 @@ janusGraphReconnectIntervalInSeconds: 3 janusGraphHealthCheckReadTimeout: 1 # The interval to try and reconnect to Elasticsearch when it is down during ASDC startup: -esReconnectIntervalInSeconds: 3 uebHealthCheckReconnectIntervalInSeconds: 15 uebHealthCheckReadTimeout: 4 diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/ILogConfiguration.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/ILogConfiguration.java new file mode 100644 index 0000000000..6862fdddc3 --- /dev/null +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/ILogConfiguration.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.common.log.api; + +public interface ILogConfiguration { + + String MDC_SERVICE_INSTANCE_ID = "ServiceInstanceID"; + String MDC_SERVER_IP_ADDRESS = "ServerIPAddress"; + String MDC_REMOTE_HOST = "RemoteHost"; + String MDC_AUDIT_MESSAGE = "AuditMessage"; + String MDC_END_TIMESTAMP = "EndTimestamp"; + String MDC_ELAPSED_TIME = "ElapsedTime"; + String MDC_PROCESS_KEY = "ProcessKey"; + String MDC_TARGET_VIRTUAL_ENTITY = "TargetVirtualEntity"; + String MDC_ERROR_CATEGORY = "ErrorCategory"; + String MDC_ERROR_CODE = "ErrorCode"; + String MDC_ERROR_DESC = "ErrorDescription"; + String MDC_CLASS_NAME = "ClassName"; + String MDC_OPT_FIELD1 = "CustomField1"; + String MDC_OPT_FIELD2 = "CustomField2"; + String MDC_OPT_FIELD3 = "CustomField3"; + String MDC_OPT_FIELD4 = "CustomField4"; + String MDC_OUTGOING_INVOCATION_ID = "OutgoingInvocationId"; + String MDC_SUPPORTABLITY_ACTION = "SupportablityAction"; + String MDC_SUPPORTABLITY_CSAR_UUID="SupportablityCsarUUID"; + String MDC_SUPPORTABLITY_CSAR_VERSION="SupportablityCsarVersion"; + String MDC_SUPPORTABLITY_COMPONENT_NAME = "SupportablityComponentName"; + String MDC_SUPPORTABLITY_COMPONENT_UUID = "SupportablityComponentUUID"; + String MDC_SUPPORTABLITY_COMPONENT_VERSION="SupportablityComponentVersion"; + String MDC_SUPPORTABLITY_STATUS_CODE = "SupportablityStatus"; +} \ No newline at end of file diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/ILogFieldsHandler.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/ILogFieldsHandler.java index 7d1783314f..ed1a19d76d 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/ILogFieldsHandler.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/ILogFieldsHandler.java @@ -1,27 +1,10 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.api; import org.openecomp.sdc.common.log.enums.Severity; +/** + * Created by dd4296 on 12/25/2017. + */ public interface ILogFieldsHandler { void startAuditTimer(); diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/ILogger.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/ILogger.java index 866498cefd..9a2ad6960a 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/ILogger.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/ILogger.java @@ -1,22 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ package org.openecomp.sdc.common.log.api; import org.openecomp.sdc.common.log.enums.LogLevel; @@ -24,6 +5,9 @@ import org.slf4j.Marker; import java.util.List; +/** + * Created by dd4296 on 12/24/2017. + */ public interface ILogger { void log(LogLevel logLevel, String message); void log(Marker marker, LogLevel logLevel, String message); diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/LogConfigurationConstants.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/LogConfigurationConstants.java deleted file mode 100644 index d1d5a3af7c..0000000000 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/api/LogConfigurationConstants.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.api; - -public final class LogConfigurationConstants { - - public static final String MDC_SERVICE_INSTANCE_ID = "ServiceInstanceID"; - public static final String MDC_SERVER_IP_ADDRESS = "ServerIPAddress"; - public static final String MDC_REMOTE_HOST = "RemoteHost"; - public static final String MDC_AUDIT_MESSAGE = "AuditMessage"; - public static final String MDC_END_TIMESTAMP = "EndTimestamp"; - public static final String MDC_ELAPSED_TIME = "ElapsedTime"; - public static final String MDC_PROCESS_KEY = "ProcessKey"; - public static final String MDC_TARGET_VIRTUAL_ENTITY = "TargetVirtualEntity"; - public static final String MDC_ERROR_CATEGORY = "ErrorCategory"; - public static final String MDC_ERROR_CODE = "ErrorCode"; - public static final String MDC_ERROR_DESC = "ErrorDescription"; - public static final String MDC_CLASS_NAME = "ClassName"; - public static final String MDC_OPT_FIELD1 = "CustomField1"; - public static final String MDC_OPT_FIELD2 = "CustomField2"; - public static final String MDC_OPT_FIELD3 = "CustomField3"; - public static final String MDC_OPT_FIELD4 = "CustomField4"; - public static final String MDC_OUTGOING_INVOCATION_ID = "OutgoingInvocationId"; - public static final String MDC_SUPPORTABLITY_ACTION = "SupportablityAction"; - public static final String MDC_SUPPORTABLITY_CSAR_UUID = "SupportablityCsarUUID"; - public static final String MDC_SUPPORTABLITY_CSAR_VERSION = "SupportablityCsarVersion"; - public static final String MDC_SUPPORTABLITY_COMPONENT_NAME = "SupportablityComponentName"; - public static final String MDC_SUPPORTABLITY_COMPONENT_UUID = "SupportablityComponentUUID"; - public static final String MDC_SUPPORTABLITY_COMPONENT_VERSION = "SupportablityComponentVersion"; - public static final String MDC_SUPPORTABLITY_STATUS_CODE = "SupportablityStatus"; -} \ No newline at end of file diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/ErrorLogOptionalData.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/ErrorLogOptionalData.java index d5279b1101..fce1143ad1 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/ErrorLogOptionalData.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/ErrorLogOptionalData.java @@ -1,37 +1,28 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.elements; public class ErrorLogOptionalData { private String targetEntity; private String targetServiceName; + public ErrorLogOptionalData() { + } + String getTargetEntity() { return targetEntity; } + private void setTargetEntity(String targetEntity) { + this.targetEntity = targetEntity; + } + String getTargetServiceName() { return targetServiceName; } + private void setTargetServiceName(String targetServiceName) { + this.targetServiceName = targetServiceName; + } + public static Builder newBuilder() { return new Builder(); } @@ -44,12 +35,12 @@ public class ErrorLogOptionalData { } public Builder targetEntity(String targetEntity) { - instance.targetEntity = targetEntity; + instance.setTargetEntity(targetEntity); return this; } public Builder targetServiceName(String targetServiceName) { - instance.targetServiceName = targetServiceName; + instance.setTargetServiceName(targetServiceName); return this; } diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandler.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandler.java index 361c255009..eb1646c612 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandler.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandler.java @@ -1,29 +1,9 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.elements; import org.apache.commons.lang3.StringUtils; import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.openecomp.sdc.common.log.api.LogConfigurationConstants; import org.openecomp.sdc.common.log.enums.ConstantsLogging; +import org.openecomp.sdc.common.log.api.ILogConfiguration; import org.openecomp.sdc.common.log.api.ILogFieldsHandler; import org.openecomp.sdc.common.log.enums.Severity; import org.slf4j.Logger; @@ -37,6 +17,8 @@ import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; +import static java.lang.Integer.valueOf; + public class LogFieldsMdcHandler implements ILogFieldsHandler { private static LogFieldsMdcHandler instanceMdcWrapper = new LogFieldsMdcHandler(); @@ -50,7 +32,7 @@ public class LogFieldsMdcHandler implements ILogFieldsHandler { .ofPattern(dateFormatPattern); protected static Logger log = LoggerFactory.getLogger(LogFieldsMdcHandler.class.getName()); protected static String hostAddress; - private static String fqdn; + protected static String fqdn; static { try { @@ -79,7 +61,7 @@ public class LogFieldsMdcHandler implements ILogFieldsHandler { public void stopAuditTimer() { //set start time if it is not set yet startAuditTimer(); - MDC.put(LogConfigurationConstants.MDC_END_TIMESTAMP, generatedTimeNow()); + MDC.put(ILogConfiguration.MDC_END_TIMESTAMP, generatedTimeNow()); setElapsedTime(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); } @@ -87,13 +69,13 @@ public class LogFieldsMdcHandler implements ILogFieldsHandler { public void stopMetricTimer() { //set start time if it is not set yet startMetricTimer(); - MDC.put(LogConfigurationConstants.MDC_END_TIMESTAMP, generatedTimeNow()); + MDC.put(ILogConfiguration.MDC_END_TIMESTAMP, generatedTimeNow()); setElapsedTime(MDC.get(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP)); } @Override public void setClassName(String className) { - MDC.put(LogConfigurationConstants.MDC_CLASS_NAME, className); + MDC.put(ILogConfiguration.MDC_CLASS_NAME, className); } @Override @@ -103,7 +85,7 @@ public class LogFieldsMdcHandler implements ILogFieldsHandler { @Override public void setServerIPAddress(String serverIPAddress) { - MDC.put(LogConfigurationConstants.MDC_SERVER_IP_ADDRESS, serverIPAddress); + MDC.put(ILogConfiguration.MDC_SERVER_IP_ADDRESS, serverIPAddress); } @Override @@ -123,7 +105,7 @@ public class LogFieldsMdcHandler implements ILogFieldsHandler { @Override public void setProcessKey(String processKey) { - MDC.put(LogConfigurationConstants.MDC_PROCESS_KEY, processKey); + MDC.put(ILogConfiguration.MDC_PROCESS_KEY, processKey); } @Override @@ -133,12 +115,12 @@ public class LogFieldsMdcHandler implements ILogFieldsHandler { @Override public void setOptCustomField1(String customField1) { - MDC.put(LogConfigurationConstants.MDC_OPT_FIELD1, customField1); + MDC.put(ILogConfiguration.MDC_OPT_FIELD1, customField1); } @Override public void setOutgoingInvocationId(String outgoingInvocationId) { - MDC.put(LogConfigurationConstants.MDC_OUTGOING_INVOCATION_ID, outgoingInvocationId); + MDC.put(ILogConfiguration.MDC_OUTGOING_INVOCATION_ID, outgoingInvocationId); } @Override @@ -155,7 +137,7 @@ public class LogFieldsMdcHandler implements ILogFieldsHandler { @Override public void setRemoteHost(String remoteHost) { - MDC.put(LogConfigurationConstants.MDC_REMOTE_HOST, remoteHost); + MDC.put(ILogConfiguration.MDC_REMOTE_HOST, remoteHost); } @Override @@ -185,7 +167,7 @@ public class LogFieldsMdcHandler implements ILogFieldsHandler { @Override public void setServiceInstanceId(String serviceInstanceId) { - MDC.put(LogConfigurationConstants.MDC_SERVICE_INSTANCE_ID, serviceInstanceId); + MDC.put(ILogConfiguration.MDC_SERVICE_INSTANCE_ID, serviceInstanceId); } @Override @@ -200,22 +182,22 @@ public class LogFieldsMdcHandler implements ILogFieldsHandler { @Override public void setTargetVirtualEntity(String targetVirtualEntity) { - MDC.put(LogConfigurationConstants.MDC_TARGET_VIRTUAL_ENTITY, targetVirtualEntity); + MDC.put(ILogConfiguration.MDC_TARGET_VIRTUAL_ENTITY, targetVirtualEntity); } @Override public void setErrorCode(int errorCode) { - MDC.put(LogConfigurationConstants.MDC_ERROR_CODE, Integer.toString(errorCode)); + MDC.put(ILogConfiguration.MDC_ERROR_CODE, valueOf(errorCode).toString()); } @Override public void setErrorCategory(String errorCategory) { - MDC.put(LogConfigurationConstants.MDC_ERROR_CATEGORY, errorCategory); + MDC.put(ILogConfiguration.MDC_ERROR_CATEGORY, errorCategory); } @Override public String getErrorCode() { - return MDC.get(LogConfigurationConstants.MDC_ERROR_CODE); + return MDC.get(ILogConfiguration.MDC_ERROR_CODE); } @Override @@ -225,7 +207,7 @@ public class LogFieldsMdcHandler implements ILogFieldsHandler { @Override public String getErrorCategory() { - return MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY); + return MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY); } @Override @@ -285,7 +267,7 @@ public class LogFieldsMdcHandler implements ILogFieldsHandler { @Override public void removeServiceInstanceId() { - MDC.remove(LogConfigurationConstants.MDC_SERVICE_INSTANCE_ID); + MDC.remove(ILogConfiguration.MDC_SERVICE_INSTANCE_ID); } @Override @@ -300,81 +282,87 @@ public class LogFieldsMdcHandler implements ILogFieldsHandler { @Override public void removeTargetVirtualEntity() { - MDC.remove(LogConfigurationConstants.MDC_TARGET_VIRTUAL_ENTITY); + MDC.remove(ILogConfiguration.MDC_TARGET_VIRTUAL_ENTITY); } @Override public void removeErrorCode() { - MDC.remove(LogConfigurationConstants.MDC_ERROR_CODE); + MDC.remove(ILogConfiguration.MDC_ERROR_CODE); } @Override public void removeErrorCategory() { - MDC.remove(LogConfigurationConstants.MDC_ERROR_CATEGORY); + MDC.remove(ILogConfiguration.MDC_ERROR_CATEGORY); } @Override public void removeErrorDescription() { - MDC.remove(LogConfigurationConstants.MDC_ERROR_DESC); + MDC.remove(ILogConfiguration.MDC_ERROR_DESC); } @Override public void setAuditMessage(String message) { - MDC.put(LogConfigurationConstants.MDC_AUDIT_MESSAGE, message); + MDC.put(ILogConfiguration.MDC_AUDIT_MESSAGE, message); } @Override public String getAuditMessage() { - return MDC.get(LogConfigurationConstants.MDC_AUDIT_MESSAGE); + return MDC.get(ILogConfiguration.MDC_AUDIT_MESSAGE); } + @Override public String getSupportablityStatusCode() { - return MDC.get(LogConfigurationConstants.MDC_SUPPORTABLITY_STATUS_CODE); + return MDC.get(ILogConfiguration.MDC_SUPPORTABLITY_STATUS_CODE); } @Override public String getSupportablityAction() { - return MDC.get(LogConfigurationConstants.MDC_SUPPORTABLITY_ACTION); + return MDC.get(ILogConfiguration.MDC_SUPPORTABLITY_ACTION); } @Override public String getRemoteHost() { - return MDC.get(LogConfigurationConstants.MDC_REMOTE_HOST); + return MDC.get(ILogConfiguration.MDC_REMOTE_HOST); } @Override public String getServerIpAddress() { - return MDC.get(LogConfigurationConstants.MDC_SERVER_IP_ADDRESS); + return MDC.get(ILogConfiguration.MDC_SERVER_IP_ADDRESS); } +// @Override +// public String getSupportablityCsarName() { +// return MDC.get(ILogConfiguration.MDC_SUPPORTABLITY_CSAR_NAME); +// } + @Override public String getSupportablityCsarUUID() { - return MDC.get(LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_UUID); + return MDC.get(ILogConfiguration.MDC_SUPPORTABLITY_CSAR_UUID); } @Override public String getSupportablityCsarVersion() { - return MDC.get(LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_VERSION); + return MDC.get(ILogConfiguration.MDC_SUPPORTABLITY_CSAR_VERSION); } @Override public String getSupportablityComponentName() { - return MDC.get(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_NAME); + return MDC.get(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_NAME); } @Override public String getSupportablityComponentUUID() { - return MDC.get(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_UUID); + return MDC.get(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_UUID); } @Override public String getSupportablityComponentVersion() { - return MDC.get(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_VERSION); + return MDC.get(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_VERSION); } @Override @@ -384,72 +372,77 @@ public class LogFieldsMdcHandler implements ILogFieldsHandler { @Override public void setSupportablityStatusCode(String statusCode) { - MDC.put(LogConfigurationConstants.MDC_SUPPORTABLITY_STATUS_CODE, statusCode); + MDC.put(ILogConfiguration.MDC_SUPPORTABLITY_STATUS_CODE, statusCode); } @Override public void setSupportablityAction(String action) { - MDC.put(LogConfigurationConstants.MDC_SUPPORTABLITY_ACTION, action); + MDC.put(ILogConfiguration.MDC_SUPPORTABLITY_ACTION, action); } @Override public void setSupportablityCsarUUID(String uuid) { - MDC.put(LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_UUID, uuid); + MDC.put(ILogConfiguration.MDC_SUPPORTABLITY_CSAR_UUID, uuid); } @Override public void setSupportablityCsarVersion(String version) { - MDC.put(LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_VERSION, version); + MDC.put(ILogConfiguration.MDC_SUPPORTABLITY_CSAR_VERSION, version); } @Override public void setSupportablityComponentName(String name) { - MDC.put(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_NAME, name); + MDC.put(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_NAME, name); } @Override public void setSupportablityComponentUUID(String uuid) { - MDC.put(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_UUID, uuid); + MDC.put(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_UUID, uuid); } @Override public void setSupportablityComponentVersion(String version) { - MDC.put(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_VERSION, version); + MDC.put(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_VERSION, version); } @Override public void removeSupportablityAction() { - MDC.remove(LogConfigurationConstants.MDC_SUPPORTABLITY_ACTION); + MDC.remove(ILogConfiguration.MDC_SUPPORTABLITY_ACTION); } @Override public void removeSupportablityComponentName() { - MDC.remove(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_NAME); + MDC.remove(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_NAME); } @Override public void removeSupportablityComponentUUID() { - MDC.remove(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_UUID); + MDC.remove(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_UUID); } @Override public void removeSupportablityComponentVersion() { - MDC.remove(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_VERSION); + MDC.remove(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_VERSION); } +// @Override +// public void removeSupportablityCsarName() { +// MDC.remove(ILogConfiguration.MDC_SUPPORTABLITY_CSAR_NAME); +// } + @Override public void removeSupportablityCsarUUID() { - MDC.remove(LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_UUID); + MDC.remove(ILogConfiguration.MDC_SUPPORTABLITY_CSAR_UUID); } @Override public void removeSupportablityCsarVersion() { - MDC.remove(LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_VERSION); + MDC.remove(ILogConfiguration.MDC_SUPPORTABLITY_CSAR_VERSION); } @Override public void removeSupportablityStatusCode() { - MDC.remove(LogConfigurationConstants.MDC_SUPPORTABLITY_STATUS_CODE); + MDC.remove(ILogConfiguration.MDC_SUPPORTABLITY_STATUS_CODE); } @Override @@ -461,10 +454,10 @@ public class LogFieldsMdcHandler implements ILogFieldsHandler { try { final LocalDateTime startTime = LocalDateTime.parse(beginTimestamp, dateTimeFormatter); final LocalDateTime endTime = LocalDateTime - .parse(MDC.get(LogConfigurationConstants.MDC_END_TIMESTAMP), dateTimeFormatter); + .parse(MDC.get(ILogConfiguration.MDC_END_TIMESTAMP), dateTimeFormatter); final Duration timeDifference = Duration.between(startTime, endTime); - MDC.put(LogConfigurationConstants.MDC_ELAPSED_TIME, String.valueOf(timeDifference.toMillis())); + MDC.put(ILogConfiguration.MDC_ELAPSED_TIME, String.valueOf(timeDifference.toMillis())); } catch (Exception ex) { log.error("failed to calculate elapsed time", ex); diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerAudit.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerAudit.java index 502b7a6871..771ecfd9d4 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerAudit.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerAudit.java @@ -1,27 +1,8 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.elements; + import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.openecomp.sdc.common.log.api.LogConfigurationConstants; +import org.openecomp.sdc.common.log.api.ILogConfiguration; import org.openecomp.sdc.common.log.api.ILogFieldsHandler; import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; import org.openecomp.sdc.common.log.enums.Severity; @@ -35,30 +16,30 @@ import java.util.Collections; import java.util.List; public class LoggerAudit extends LoggerBase { - private static List mandatoryFields = new ArrayList<>(Arrays.asList( + private static ArrayList mandatoryFields = new ArrayList<>(Arrays.asList( ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, - LogConfigurationConstants.MDC_END_TIMESTAMP, + ILogConfiguration.MDC_END_TIMESTAMP, ONAPLogConstants.MDCs.REQUEST_ID, ONAPLogConstants.MDCs.SERVICE_NAME, ONAPLogConstants.MDCs.PARTNER_NAME, ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.MDCs.RESPONSE_CODE, - LogConfigurationConstants.MDC_SERVICE_INSTANCE_ID, + ILogConfiguration.MDC_SERVICE_INSTANCE_ID, ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, - LogConfigurationConstants.MDC_ELAPSED_TIME, - LogConfigurationConstants.MDC_SERVER_IP_ADDRESS, + ILogConfiguration.MDC_ELAPSED_TIME, + ILogConfiguration.MDC_SERVER_IP_ADDRESS, ONAPLogConstants.MDCs.SERVER_FQDN)); - private static List optionalFields = new ArrayList<>(Arrays.asList( + private static ArrayList optionalFields = new ArrayList<>(Arrays.asList( ONAPLogConstants.MDCs.INSTANCE_UUID, ONAPLogConstants.MDCs.RESPONSE_SEVERITY, - LogConfigurationConstants.MDC_REMOTE_HOST, - LogConfigurationConstants.MDC_CLASS_NAME, - LogConfigurationConstants.MDC_PROCESS_KEY, - LogConfigurationConstants.MDC_OPT_FIELD1, - LogConfigurationConstants.MDC_OPT_FIELD2, - LogConfigurationConstants.MDC_OPT_FIELD3, - LogConfigurationConstants.MDC_OPT_FIELD4)); + ILogConfiguration.MDC_REMOTE_HOST, + ILogConfiguration.MDC_CLASS_NAME, + ILogConfiguration.MDC_PROCESS_KEY, + ILogConfiguration.MDC_OPT_FIELD1, + ILogConfiguration.MDC_OPT_FIELD2, + ILogConfiguration.MDC_OPT_FIELD3, + ILogConfiguration.MDC_OPT_FIELD4)); LoggerAudit(ILogFieldsHandler ecompMdcWrapper, Logger logger) { //TODO Andrey, set default marker @@ -85,7 +66,7 @@ public class LoggerAudit extends LoggerBase { } public LoggerAudit setOptClassName(String className) { - MDC.put(LogConfigurationConstants.MDC_CLASS_NAME, className); + MDC.put(ILogConfiguration.MDC_CLASS_NAME, className); return this; } diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerBase.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerBase.java index 5b2bfad5b9..4ee6039d32 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerBase.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerBase.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.elements; import com.google.common.annotations.VisibleForTesting; @@ -38,6 +18,12 @@ import java.util.Arrays; import java.util.List; import java.util.UUID; + +/** + * Created by mm288v on 12/27/2017. + * This class holds the common behavior of all Loger-Typed classes. + * The Concrete loggers shoudl derive from this one. + */ public abstract class LoggerBase implements ILogger { private final Logger myLogger; private final Marker myMarker; diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerDebug.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerDebug.java index dc8c4b4c16..cebe7bac51 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerDebug.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerDebug.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.elements; import org.onap.logging.ref.slf4j.ONAPLogConstants; @@ -33,7 +13,7 @@ import java.util.List; public class LoggerDebug extends LoggerBase { - private static List mandatoryFields = new ArrayList<>(Arrays.asList(ONAPLogConstants.MDCs.REQUEST_ID)); + private static ArrayList mandatoryFields = new ArrayList<>(Arrays.asList(ONAPLogConstants.MDCs.REQUEST_ID)); LoggerDebug(ILogFieldsHandler ecompMdcWrapper, Logger logger) { super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.DEBUG_MARKER.text()), logger); diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerError.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerError.java index a38f16df98..fbf610638b 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerError.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerError.java @@ -1,28 +1,8 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.elements; import org.apache.commons.lang3.StringUtils; import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.openecomp.sdc.common.log.api.LogConfigurationConstants; +import org.openecomp.sdc.common.log.api.ILogConfiguration; import org.openecomp.sdc.common.log.api.ILogFieldsHandler; import org.openecomp.sdc.common.log.enums.EcompErrorSeverity; import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; @@ -40,8 +20,8 @@ public class LoggerError extends LoggerBase { private static ArrayList mandatoryFields = new ArrayList<>(Arrays.asList( ONAPLogConstants.MDCs.REQUEST_ID, ONAPLogConstants.MDCs.SERVICE_NAME, - LogConfigurationConstants.MDC_ERROR_CATEGORY, - LogConfigurationConstants.MDC_ERROR_CODE)); + ILogConfiguration.MDC_ERROR_CATEGORY, + ILogConfiguration.MDC_ERROR_CODE)); public static final String defaultServiceName = "SDC catalog"; diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerFactory.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerFactory.java index 59e2777966..f2f33b2457 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerFactory.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerFactory.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.elements; import org.slf4j.Logger; @@ -35,19 +15,19 @@ public class LoggerFactory { @SuppressWarnings("unchecked") public static V getLogger(Class type, Logger logger) { - if (type.getName().equals(LoggerAudit.class.getName())) { + if (type.isAssignableFrom(LoggerAudit.class)) { return (V) new LoggerAudit(new LogFieldsMdcHandler(), logger); } - if (type.getName().equals(LoggerDebug.class.getName())) { + if (type.isAssignableFrom(LoggerDebug.class)) { return (V) new LoggerDebug(new LogFieldsMdcHandler(), logger); } - if (type.getName().equals(LoggerMetric.class.getName())) { + if (type.isAssignableFrom(LoggerMetric.class)) { return (V) new LoggerMetric(new LogFieldsMdcHandler(), logger); } - if (type.getName().equals(LoggerError.class.getName())) { + if (type.isAssignableFrom(LoggerError.class)) { return (V) new LoggerError(new LogFieldsMdcHandler(), logger); } @@ -57,19 +37,19 @@ public class LoggerFactory { @SuppressWarnings("unchecked") public static V getMdcLogger(Class type, Logger logger) { - if (type.getName().equals(LoggerAudit.class.getName())) { + if (type.isAssignableFrom(LoggerAudit.class)) { return (V) new LoggerAudit(LogFieldsMdcHandler.getInstance(), logger); } - if (type.getName().equals(LoggerDebug.class.getName())) { + if (type.isAssignableFrom(LoggerDebug.class)) { return (V) new LoggerDebug(LogFieldsMdcHandler.getInstance(), logger); } - if (type.getName().equals(LoggerMetric.class.getName())) { + if (type.isAssignableFrom(LoggerMetric.class)) { return (V) new LoggerMetric(LogFieldsMdcHandler.getInstance(), logger); } - if (type.getName().equals(LoggerError.class.getName())) { + if (type.isAssignableFrom(LoggerError.class)) { return (V) new LoggerError(LogFieldsMdcHandler.getInstance(), logger); } diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerMetric.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerMetric.java index 3dbcf1dde3..8af85ea1a3 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerMetric.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerMetric.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.elements; import org.openecomp.sdc.common.log.api.ILogFieldsHandler; @@ -33,11 +13,11 @@ import java.util.Arrays; import java.util.List; import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.*; -import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.*; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.*; public class LoggerMetric extends LoggerBase { - private static List mandatoryFields = new ArrayList<>(Arrays.asList( + private static ArrayList mandatoryFields = new ArrayList<>(Arrays.asList( INVOKE_TIMESTAMP, MDC_END_TIMESTAMP, REQUEST_ID, @@ -51,7 +31,7 @@ public class LoggerMetric extends LoggerBase { MDC_SERVER_IP_ADDRESS, SERVER_FQDN)); - private static List optionalFields = new ArrayList<>(Arrays.asList( + private static ArrayList optionalFields = new ArrayList<>(Arrays.asList( MDC_TARGET_VIRTUAL_ENTITY, TARGET_ENTITY, TARGET_SERVICE_NAME, diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerSupportability.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerSupportability.java index 849add3625..b3b91b96be 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerSupportability.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerSupportability.java @@ -1,26 +1,6 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.elements; -import org.openecomp.sdc.common.log.api.LogConfigurationConstants; +import org.openecomp.sdc.common.log.api.ILogConfiguration; import org.openecomp.sdc.common.log.api.ILogFieldsHandler; import org.openecomp.sdc.common.log.enums.LogLevel; import org.openecomp.sdc.common.log.enums.LogMarkers; @@ -53,23 +33,23 @@ public class LoggerSupportability extends LoggerBase { log(action, null, statusCode, message, params); } - private static List mandatoryFields = new ArrayList<>(Arrays.asList( - LogConfigurationConstants.MDC_SUPPORTABLITY_ACTION, - LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_UUID, - LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_VERSION, - LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_NAME, - LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_UUID, - LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_VERSION, - LogConfigurationConstants.MDC_SUPPORTABLITY_STATUS_CODE)); + private static ArrayList mandatoryFields = new ArrayList<>(Arrays.asList( + ILogConfiguration.MDC_SUPPORTABLITY_ACTION, + ILogConfiguration.MDC_SUPPORTABLITY_CSAR_UUID, + ILogConfiguration.MDC_SUPPORTABLITY_CSAR_VERSION, + ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_NAME, + ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_UUID, + ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_VERSION, + ILogConfiguration.MDC_SUPPORTABLITY_STATUS_CODE)); private void fillFieldsBeforeLogging(LoggerSupportabilityActions action, Map componentMetaData,StatusCode statusCode) { clear(); if (componentMetaData!=null){ - ecompLogFieldsHandler.setSupportablityCsarUUID(componentMetaData.get(LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_UUID)); - ecompLogFieldsHandler.setSupportablityCsarVersion(componentMetaData.get(LogConfigurationConstants.MDC_SUPPORTABLITY_CSAR_VERSION)); - ecompLogFieldsHandler.setSupportablityComponentName(componentMetaData.get(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_NAME)); - ecompLogFieldsHandler.setSupportablityComponentUUID(componentMetaData.get(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_UUID)); - ecompLogFieldsHandler.setSupportablityComponentVersion(componentMetaData.get(LogConfigurationConstants.MDC_SUPPORTABLITY_COMPONENT_VERSION)); + ecompLogFieldsHandler.setSupportablityCsarUUID(componentMetaData.get(ILogConfiguration.MDC_SUPPORTABLITY_CSAR_UUID)); + ecompLogFieldsHandler.setSupportablityCsarVersion(componentMetaData.get(ILogConfiguration.MDC_SUPPORTABLITY_CSAR_VERSION)); + ecompLogFieldsHandler.setSupportablityComponentName(componentMetaData.get(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_NAME)); + ecompLogFieldsHandler.setSupportablityComponentUUID(componentMetaData.get(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_UUID)); + ecompLogFieldsHandler.setSupportablityComponentVersion(componentMetaData.get(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_VERSION)); } ecompLogFieldsHandler.setSupportablityAction(action.getName()); ecompLogFieldsHandler.setSupportablityStatusCode(statusCode.getStatusCodeEnum()); diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/ConstantsLogging.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/ConstantsLogging.java index 34606dcebd..025de545a0 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/ConstantsLogging.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/ConstantsLogging.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.enums; public final class ConstantsLogging { diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/EcompErrorSeverity.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/EcompErrorSeverity.java index 4d21d8c8c6..e88a074f0a 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/EcompErrorSeverity.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/EcompErrorSeverity.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.enums; public enum EcompErrorSeverity { diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/EcompLoggerErrorCode.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/EcompLoggerErrorCode.java index db174b4096..780b24d0e5 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/EcompLoggerErrorCode.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/EcompLoggerErrorCode.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * SDC * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LogLevel.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LogLevel.java index aaee7512bd..5b1ec9d4a9 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LogLevel.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LogLevel.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * SDC * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,8 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.openecomp.sdc.common.log.enums; +/** + * Created by dd4296 on 12/14/2017. + */ public enum LogLevel { INFO, WARN, diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LogMarkers.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LogMarkers.java index 7b12ded745..4f98c556e8 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LogMarkers.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LogMarkers.java @@ -1,25 +1,9 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.enums; +/** + * Created by mm288v on 12/27/2017. + * This enum reflects the Marker text in logback.xml file per each ecomp marker + */ public enum LogMarkers { DEBUG_MARKER("DEBUG_MARKER"), ERROR_MARKER("ERROR_MARKER"), diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LoggerSupportabilityActions.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LoggerSupportabilityActions.java index d831700dec..95594a3469 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LoggerSupportabilityActions.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/LoggerSupportabilityActions.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.enums; public enum LoggerSupportabilityActions { diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/Severity.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/Severity.java index 0e90d57c8e..15a6039f7f 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/Severity.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/Severity.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * SDC * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,6 +20,9 @@ package org.openecomp.sdc.common.log.enums; +/** + * Created by dd4296 on 12/14/2017. + */ public enum Severity { OK(0), WARNING(1), diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/StatusCode.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/StatusCode.java index 4ed65df97b..8ede6f9d6e 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/StatusCode.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/enums/StatusCode.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.enums; public enum StatusCode { diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/utils/EcompLogErrorCode.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/utils/EcompLogErrorCode.java index 9c90529d22..ce33480ca2 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/utils/EcompLogErrorCode.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/utils/EcompLogErrorCode.java @@ -1,31 +1,19 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.utils; + public enum EcompLogErrorCode { E_399("Internal Invalid Object. Description: %s"), - E_210("Connection problem towards U-EB server. Reason: %s"); + E_210( + "Connection problem towards U-EB server. Reason: %s"); String description; + String resolution; + + EcompLogErrorCode(String description, String resolution) { + this.description = description; + this.resolution = resolution; + } EcompLogErrorCode(String description) { this.description = description; @@ -39,4 +27,12 @@ public enum EcompLogErrorCode { this.description = description; } -} + public String getResolution() { + return resolution; + } + + public void setResolution(String resolution) { + this.resolution = resolution; + } + + } diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/utils/LoggingThreadLocalsHolder.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/utils/LoggingThreadLocalsHolder.java index 3d7a16b846..c621a2a975 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/utils/LoggingThreadLocalsHolder.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/utils/LoggingThreadLocalsHolder.java @@ -22,9 +22,6 @@ package org.openecomp.sdc.common.log.utils; public class LoggingThreadLocalsHolder { - - private LoggingThreadLocalsHolder() { - } private static final ThreadLocal uuidThreadLocal = new ThreadLocal<>(); diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/Logger.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/Logger.java index 9c2bfec126..8f733b4f5e 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/Logger.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/Logger.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.wrappers; import com.google.common.annotations.VisibleForTesting; @@ -131,14 +111,13 @@ public class Logger implements org.slf4j.Logger { metric.log(LogLevel.INFO, msg, params); } - public void invoke(String remoteHost, String targetEntity, String targetServiceName, String serviceName, String msg, Object... params) { + public void invoke(String targetEntity, String targetServiceName, String serviceName, String msg, Object... params) { String invocationId = UUID.randomUUID().toString(); String requestID = UUID.randomUUID().toString(); metric.startTimer() .stopTimer() - .setRemoteHost(remoteHost) .setOutgoingInvocationId(invocationId) .setTargetServiceName(targetServiceName) .setTargetEntity(targetEntity) diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcAudit.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcAudit.java index b2db66ed00..b8c1b268e1 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcAudit.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcAudit.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.wrappers; import org.apache.commons.lang3.StringUtils; diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcUtilBase.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcUtilBase.java index cec429a000..6ca71281d3 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcUtilBase.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcUtilBase.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.wrappers; import org.apache.commons.lang3.StringUtils; @@ -31,6 +11,12 @@ import java.util.StringTokenizer; import static java.net.HttpURLConnection.*; +/** + * Created by dd4296 on 12/20/2017. + * + * base class for metric and audit log logging + * holding the specific logic for data extraction + */ public class LoggerSdcUtilBase { protected static Logger log = LoggerFactory.getLogger(LoggerSdcUtilBase.class.getName()); @@ -92,8 +78,9 @@ public class LoggerSdcUtilBase { case HTTP_BAD_METHOD: case HTTP_PROXY_AUTH: return true; - default: return false; } + + return false; } private boolean isDataError(int httpResponseCode) { @@ -106,8 +93,9 @@ public class LoggerSdcUtilBase { case HTTP_ENTITY_TOO_LARGE: case HTTP_UNSUPPORTED_TYPE: return true; - default: return false; } + + return false; } private boolean isSchemaError(int httpResponseCode) { @@ -199,6 +187,9 @@ public class LoggerSdcUtilBase { } private boolean isFound(String value) { - return (StringUtils.isNotEmpty(value)); + if (StringUtils.isNotEmpty(value)) { + return true; + } + return false; } } \ No newline at end of file diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandlerTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandlerTest.java index 1634115b06..c6b854ea06 100644 --- a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandlerTest.java +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandlerTest.java @@ -26,7 +26,7 @@ import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.slf4j.MDC; import static org.junit.Assert.*; -import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.*; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.*; public class LogFieldsMdcHandlerTest { diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAsdcUtilTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAsdcUtilTest.java index 4b0533ae24..1bd733664e 100644 --- a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAsdcUtilTest.java +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAsdcUtilTest.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.elements; @@ -45,16 +25,21 @@ import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; +/** + * Created by dd4296 on 12/19/2017. + * + * test get partner name + */ @RunWith(MockitoJUnitRunner.class) public class LoggerAsdcUtilTest { - private static final String chromeUserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"; - private static final String firefoxUserAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.13) Gecko/20080313 Firefox"; - private static final String explorerUserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0)"; + private final String chromeUserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"; + private final String firefoxUserAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.13) Gecko/20080313 Firefox"; + private final String explorerUserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0)"; - private static final String testUserId = "ml007"; - private static final String urlWithUserName = "/api/v1/user/" + testUserId; - private static final String xOnapPartnerName = "ml007"; + private final String testUserId = "ml007"; + private final String urlWithUserName = "/api/v1/user/" + testUserId; + private final String xOnapPartnerName = "ml007"; class SdcEelfAuditTest extends LoggerSdcAudit { diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAuditTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAuditTest.java index 7ca1cf16cc..8c37e23d97 100644 --- a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAuditTest.java +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAuditTest.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.elements; import org.junit.After; @@ -38,7 +18,14 @@ import java.net.UnknownHostException; import java.util.UUID; import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.*; -import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.*; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.*; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_CLASS_NAME; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_ELAPSED_TIME; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_END_TIMESTAMP; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_PROCESS_KEY; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_REMOTE_HOST; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_SERVER_IP_ADDRESS; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_SERVICE_INSTANCE_ID; import static org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler.hostAddress; import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.DATA_ERROR; diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerBaseTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerBaseTest.java index 91e1aab267..b423102cb3 100644 --- a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerBaseTest.java +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerBaseTest.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.elements; import org.junit.Test; diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerDebugTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerDebugTest.java index 020b55cba6..404f5c1c62 100644 --- a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerDebugTest.java +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerDebugTest.java @@ -1,25 +1,9 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.elements; +/** + * Created by dd4296 on 12/25/2017. + */ + import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -37,7 +21,7 @@ import java.net.UnknownHostException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE; -import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.*; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.*; @RunWith(MockitoJUnitRunner.class) public class LoggerDebugTest { diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerErrorTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerErrorTest.java index 06376ed48f..8d54397c88 100644 --- a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerErrorTest.java +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerErrorTest.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.elements; import org.junit.Before; @@ -34,7 +14,7 @@ import org.slf4j.Logger; import org.slf4j.MDC; import static org.junit.Assert.assertEquals; -import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.MDC_ERROR_CODE; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_ERROR_CODE; @RunWith(MockitoJUnitRunner.class) public class LoggerErrorTest { diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerMetricTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerMetricTest.java index 3bd1afcce9..0d8c80797d 100644 --- a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerMetricTest.java +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerMetricTest.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.elements; import org.junit.After; @@ -28,6 +8,7 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.enums.Severity; import org.openecomp.sdc.common.log.utils.LoggingThreadLocalsHolder; import org.slf4j.Logger; import org.slf4j.MDC; @@ -39,7 +20,14 @@ import java.util.UUID; import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.*; import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.COMPLETE; -import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.*; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_CLASS_NAME; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_ELAPSED_TIME; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_END_TIMESTAMP; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_PROCESS_KEY; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_REMOTE_HOST; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_SERVER_IP_ADDRESS; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_TARGET_VIRTUAL_ENTITY; import static org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler.hostAddress; /** diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/wrappers/LoggerTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/wrappers/LoggerTest.java index fd66efffc7..da721fa4f5 100644 --- a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/wrappers/LoggerTest.java +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/wrappers/LoggerTest.java @@ -1,23 +1,3 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.openecomp.sdc.common.log.wrappers; import org.junit.Before; @@ -29,7 +9,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.openecomp.sdc.common.log.api.LogConfigurationConstants; +import org.openecomp.sdc.common.log.api.ILogConfiguration; import org.openecomp.sdc.common.log.elements.ErrorLogOptionalData; import org.openecomp.sdc.common.log.elements.LoggerError; import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; @@ -46,14 +26,12 @@ import javax.ws.rs.core.UriInfo; import java.net.URI; import java.net.URISyntaxException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.REQUEST_ID; import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.SERVICE_NAME; -import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.MDC_ERROR_CATEGORY; -import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.MDC_ERROR_CODE; +import static org.openecomp.sdc.common.log.api.ILogConfiguration.*; @RunWith(MockitoJUnitRunner.class) public class LoggerTest { @@ -63,6 +41,7 @@ public class LoggerTest { private final static String serviceName = "testService"; private final static String message = "Logger message"; private final static String exceptionMsg= "Exception testing"; + private final static String missingFieldsMessageFragment = "mandatory parameters for ECOMP logging"; @Mock private org.slf4j.Logger logger; @@ -91,8 +70,8 @@ public class LoggerTest { verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); assertEquals(message, captor.getValue()); - assertEquals(String.valueOf(EcompLoggerErrorCode.PERMISSION_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); - assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(String.valueOf(EcompLoggerErrorCode.PERMISSION_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY)); assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); assertEquals(serviceName, MDC.get(SERVICE_NAME)); } @@ -104,8 +83,8 @@ public class LoggerTest { verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); assertEquals(message, captor.getValue()); - assertEquals(String.valueOf(EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); - assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(String.valueOf(EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY)); assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); assertEquals(serviceName, MDC.get(SERVICE_NAME)); } @@ -117,8 +96,8 @@ public class LoggerTest { verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); assertEquals(message, captor.getValue()); - assertEquals(String.valueOf(EcompLoggerErrorCode.PERMISSION_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); - assertEquals(LogLevel.FATAL.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(String.valueOf(EcompLoggerErrorCode.PERMISSION_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE)); + assertEquals(LogLevel.FATAL.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY)); assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); assertEquals(serviceName, MDC.get(SERVICE_NAME)); } @@ -132,8 +111,8 @@ public class LoggerTest { commonLogger.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); verify(logger).warn(any(Marker.class), captor.capture(), any(Object[].class)); assertEquals(message, captor.getValue()); - assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); - assertEquals(LogLevel.WARN.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE)); + assertEquals(LogLevel.WARN.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY)); assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); assertEquals(serviceName, MDC.get(SERVICE_NAME)); assertEquals(targetServiceName, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); @@ -147,8 +126,8 @@ public class LoggerTest { commonLogger.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); verify(logger).warn(any(Marker.class), captor.capture(), any(Object[].class)); assertEquals(message, captor.getValue()); - assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); - assertEquals(LogLevel.WARN.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE)); + assertEquals(LogLevel.WARN.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY)); assertEquals(null, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); assertEquals(serviceName, MDC.get(SERVICE_NAME)); assertEquals(targetServiceName, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); @@ -162,8 +141,8 @@ public class LoggerTest { commonLogger.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); verify(logger).warn(any(Marker.class), captor.capture(), any(Object[].class)); assertEquals(message, captor.getValue()); - assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); - assertEquals(LogLevel.WARN.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE)); + assertEquals(LogLevel.WARN.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY)); assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); assertEquals(serviceName, MDC.get(SERVICE_NAME)); assertEquals(null, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); @@ -179,8 +158,8 @@ public class LoggerTest { commonLogger.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); assertEquals(message, captor.getValue()); - assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); - assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY)); assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); assertEquals(serviceName, MDC.get(SERVICE_NAME)); assertEquals(targetServiceName, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); @@ -194,8 +173,8 @@ public class LoggerTest { commonLogger.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); assertEquals(message, captor.getValue()); - assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); - assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY)); assertEquals(null, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); assertEquals(serviceName, MDC.get(SERVICE_NAME)); assertEquals(targetServiceName, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); @@ -209,8 +188,8 @@ public class LoggerTest { commonLogger.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); assertEquals(message, captor.getValue()); - assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); - assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY)); assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); assertEquals(serviceName, MDC.get(SERVICE_NAME)); assertEquals(null, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); @@ -230,8 +209,8 @@ public class LoggerTest { commonLogger.error(message); verify(logger).error(any(Marker.class), eq(message), any(Object[].class)); - assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); - assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY)); assertNull(MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); assertEquals(LoggerError.defaultServiceName, MDC.get(SERVICE_NAME)); } @@ -268,13 +247,14 @@ public class LoggerTest { @Test public void validateErrorLogWithExceptionWhenErrorSettingsProvidedPartially() { LoggingThreadLocalsHolder.setUuid("uuid"); + final String logFieldsNotProvidedMsg = "mandatory parameters for ECOMP logging, missing fields: ServiceName PartnerName"; when(logger.isWarnEnabled()).thenReturn(true); commonLogger.warn(message, new NullPointerException(exceptionMsg)); //the expected warn message verify(logger).warn(any(Marker.class), contains(message), any(Object[].class)); - assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); - assertEquals(LogLevel.WARN.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE)); + assertEquals(LogLevel.WARN.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY)); assertEquals("uuid", MDC.get(REQUEST_ID)); assertNull(MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); assertEquals(LoggerError.defaultServiceName, MDC.get(SERVICE_NAME)); @@ -310,7 +290,7 @@ public class LoggerTest { @Test public void verifyMdcValuesAreStoredWhenAuditAndErrorLoggersAreInvokedSequentially() throws URISyntaxException { final String uuid = "12345"; - final String messageInt = "message"; + final String message = "message"; when(requestContext.getHeaderString(anyString())).thenReturn("ab2222"); when(requestContext.getUriInfo()).thenReturn(uriInfo); when(logger.isErrorEnabled()).thenReturn(true); @@ -323,11 +303,11 @@ public class LoggerTest { LoggerSdcAudit audit = new LoggerSdcAudit(this.getClass()); LoggingThreadLocalsHolder.setUuid(uuid); audit.startLog(requestContext); - audit.logExit("abc.log.com", requestContext, statusType, LogLevel.INFO, Severity.OK, messageInt, + audit.logExit("abc.log.com", requestContext, statusType, LogLevel.INFO, Severity.OK, message, MarkerFactory.getMarker(ONAPLogConstants.Markers.EXIT.getName())); - commonLogger.error(messageInt); - verify(logger).error(any(Marker.class), eq(messageInt), any(Object[].class)); + commonLogger.error(message); + verify(logger).error(any(Marker.class), eq(message), any(Object[].class)); assertEquals(uuid, MDC.get(REQUEST_ID)); assertEquals("/", MDC.get(SERVICE_NAME)); assertEquals(LogLevel.ERROR.name(), MDC.get(MDC_ERROR_CATEGORY)); @@ -356,7 +336,7 @@ public class LoggerTest { @Test public void verifyMdcValuesAreStoredWhenTraceLoggerIsInvokedAfterAuditStart() throws URISyntaxException { final String uuid = "12345"; - final String messageInt = "message"; + final String message = "message"; when(requestContext.getHeaderString(anyString())).thenReturn("ab2222"); when(requestContext.getUriInfo()).thenReturn(uriInfo); when(logger.isTraceEnabled()).thenReturn(true); @@ -368,9 +348,9 @@ public class LoggerTest { LoggingThreadLocalsHolder.setUuid(uuid); audit.startLog(requestContext); - commonLogger.trace(messageInt); + commonLogger.trace(message); verify(logger).trace(any(Marker.class), captor.capture(), eq((Object[])null)); - assertEquals(messageInt, captor.getValue()); + assertEquals(message, captor.getValue()); assertEquals(uuid, MDC.get(REQUEST_ID)); } diff --git a/common-be/pom.xml b/common-be/pom.xml index 97dcc6a11e..e361da30b7 100644 --- a/common-be/pom.xml +++ b/common-be/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.openecomp.sdc.be @@ -100,6 +100,35 @@ test + + + org.togglz + togglz-core + ${togglz.version} + + + + + org.togglz + togglz-servlet + ${togglz.version} + + + + + org.togglz + togglz-console + ${togglz.version} + + + + + org.togglz + togglz-testing + ${togglz.version} + test + + diff --git a/common-be/src/main/java/org/openecomp/sdc/be/config/NonManoArtifactType.java b/common-be/src/main/java/org/openecomp/sdc/be/config/NonManoArtifactType.java index 62e11bba00..8f35b60bf8 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/config/NonManoArtifactType.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/config/NonManoArtifactType.java @@ -19,11 +19,12 @@ package org.openecomp.sdc.be.config; -import java.util.Arrays; -import java.util.Optional; import lombok.AllArgsConstructor; import lombok.Getter; +import java.util.Arrays; +import java.util.Optional; + /** * Stores non mano artifact types. */ diff --git a/common-be/src/main/java/org/openecomp/sdc/be/config/NonManoConfiguration.java b/common-be/src/main/java/org/openecomp/sdc/be/config/NonManoConfiguration.java index 9471fed0fe..93d09a2e7a 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/config/NonManoConfiguration.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/config/NonManoConfiguration.java @@ -19,10 +19,10 @@ package org.openecomp.sdc.be.config; -import java.util.Map; - import lombok.Data; +import java.util.Map; + /** * Represents the non-mano configuration yaml. */ diff --git a/common-be/src/main/java/org/openecomp/sdc/be/config/NonManoConfigurationManager.java b/common-be/src/main/java/org/openecomp/sdc/be/config/NonManoConfigurationManager.java index 028f16ab6e..12813f231d 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/config/NonManoConfigurationManager.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/config/NonManoConfigurationManager.java @@ -19,13 +19,14 @@ package org.openecomp.sdc.be.config; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; import org.apache.commons.io.IOUtils; import org.onap.sdc.tosca.parser.utils.YamlToObjectConverter; import org.openecomp.sdc.be.config.exception.LoadConfigurationException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + /** * Singleton that loads and stores the Non Mano configuration */ @@ -47,7 +48,7 @@ public class NonManoConfigurationManager { } final String data; try { - data = IOUtils.toString(configYamlAsStream, StandardCharsets.UTF_8); + data = IOUtils.toString(configYamlAsStream, String.valueOf(StandardCharsets.UTF_8)); } catch (final IOException e) { throw new LoadConfigurationException("Could not parse non-mano configuration file 'config/nonManoConfig.yaml' to string", e); } diff --git a/common-be/src/main/java/org/openecomp/sdc/be/csar/pnf/PnfSoftwareInformation.java b/common-be/src/main/java/org/openecomp/sdc/be/csar/pnf/PnfSoftwareInformation.java index d714faaa23..cb3ef1486e 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/csar/pnf/PnfSoftwareInformation.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/csar/pnf/PnfSoftwareInformation.java @@ -19,14 +19,15 @@ package org.openecomp.sdc.be.csar.pnf; -import java.util.LinkedHashSet; -import java.util.Set; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import org.apache.commons.collections.CollectionUtils; +import java.util.LinkedHashSet; +import java.util.Set; + /** * Represents the Pnf software information non-mano yaml */ diff --git a/common-be/src/main/java/org/openecomp/sdc/be/csar/pnf/SoftwareInformationArtifactYamlParser.java b/common-be/src/main/java/org/openecomp/sdc/be/csar/pnf/SoftwareInformationArtifactYamlParser.java index e5696afaed..ad67962de4 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/csar/pnf/SoftwareInformationArtifactYamlParser.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/csar/pnf/SoftwareInformationArtifactYamlParser.java @@ -19,11 +19,6 @@ package org.openecomp.sdc.be.csar.pnf; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Optional; import org.apache.commons.collections.CollectionUtils; import org.onap.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.be.csar.pnf.PnfSoftwareInformation.PnfSoftwareInformationField; @@ -32,6 +27,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.error.YAMLException; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Optional; + /** * Handles the parsing of the non-mano software information file. */ diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ComponentMetadataDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ComponentMetadataDataDefinition.java index 4cee3ff49d..4feb026fd6 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ComponentMetadataDataDefinition.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ComponentMetadataDataDefinition.java @@ -21,6 +21,7 @@ package org.openecomp.sdc.be.datatypes.components; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFieldsExtractor; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.common.log.wrappers.Logger; @@ -203,6 +204,33 @@ public abstract class ComponentMetadataDataDefinition extends ToscaDataDefinitio this.archiveTime = other.getArchiveTime(); } + public ComponentMetadataDataDefinition(JsonPresentationFieldsExtractor extractor){ + this.uniqueId = extractor.getUniqueId(); + this.name = extractor.getName(); + this.version = extractor.getVersion(); + this.isHighestVersion = extractor.isHighestVersion(); + this.creationDate = extractor.getCreationDate(); + this.lastUpdateDate = extractor.getLastUpdateDate(); + this.description = extractor.getDescription(); + this.state = extractor.getState(); + this.tags = extractor.getTags(); + this.icon = extractor.getIcon(); + this.contactId = extractor.getContactId(); + this.UUID = extractor.getUUID(); + this.normalizedName = extractor.getNormalizedName(); + this.systemName = extractor.getSystemName(); + this.isDeleted = extractor.isDeleted(); + this.projectCode = extractor.getProjectCode(); + this.csarUUID = extractor.getCsarUuid(); + this.csarVersion = extractor.getCsarVersion(); + this.importedToscaChecksum = extractor.getImportedToscaChecksum(); + this.invariantUUID = extractor.getInvariantUuid(); + this.isArchived = extractor.isArchived(); + this.isVspArchived = extractor.isVspArchived(); + this.archiveTime = extractor.getArchiveTime(); + } + + public String getUniqueId() { return uniqueId; } diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ResourceMetadataDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ResourceMetadataDataDefinition.java index 3a48286280..8b78450358 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ResourceMetadataDataDefinition.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ResourceMetadataDataDefinition.java @@ -20,8 +20,10 @@ package org.openecomp.sdc.be.datatypes.components; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFieldsExtractor; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; + public class ResourceMetadataDataDefinition extends ComponentMetadataDataDefinition { private String vendorName; @@ -48,6 +50,16 @@ public class ResourceMetadataDataDefinition extends ComponentMetadataDataDefinit this.isAbstract = other.isHighestVersion(); this.resourceType = other.getResourceType(); this.toscaResourceName = other.getToscaResourceName(); + } + + public ResourceMetadataDataDefinition(JsonPresentationFieldsExtractor extractor){ + super(extractor); + this.vendorName = extractor.getVendorName(); + this.vendorRelease = extractor.getVendorRelease(); + this.resourceVendorModelNumber = extractor.getResourceVendorModelNumber(); + this.isAbstract = extractor.isAbstract(); + this.resourceType = extractor.getResourceType(); + this.toscaResourceName = extractor.getToscaResourceName(); } public String getVendorName() { diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinition.java index 0ef10d4c95..483c6fcabc 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinition.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinition.java @@ -20,6 +20,10 @@ package org.openecomp.sdc.be.datatypes.components; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFieldsExtractor; + + + public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefinition { private static final String EMPTY_STR = ""; @@ -27,6 +31,7 @@ public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefiniti private String serviceType; private String serviceRole; private String instantiationType = EMPTY_STR; + private String serviceFunction; private Boolean ecompGeneratedNaming = true; @@ -38,12 +43,22 @@ public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefiniti super(); serviceType = ""; serviceRole = ""; + serviceFunction = ""; } + public ServiceMetadataDataDefinition(ServiceMetadataDataDefinition other) { super(other); serviceType = other.getServiceType(); serviceRole = other.getServiceRole(); + serviceFunction = other.getServiceFunction(); + } + + public ServiceMetadataDataDefinition(JsonPresentationFieldsExtractor extractor){ + super(extractor); + serviceType = extractor.getServiceType(); + serviceRole = extractor.getServiceRole(); + serviceFunction = extractor.getServiceFunction(); } public String getDistributionStatus() { @@ -82,6 +97,10 @@ public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefiniti return ecompGeneratedNaming; } + public Boolean getEcompGeneratedNaming() { + return ecompGeneratedNaming; + } + public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) { this.ecompGeneratedNaming = ecompGeneratedNaming; } @@ -102,18 +121,27 @@ public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefiniti this.environmentContext = environmentContext; } - @Override - public String toString() { - return "ServiceMetadataDataDefinition{" - + "distributionStatus='" + distributionStatus + '\'' - + ", serviceType='" + serviceType + '\'' - + ", serviceRole='" + serviceRole + '\'' - + ", ecompGeneratedNaming=" + ecompGeneratedNaming - + ", namingPolicy='" + namingPolicy + '\'' - + ", environmentContext='" + environmentContext + '\'' - + ", instantiationType='" + instantiationType + '\'' - + '}'; - } + public String getServiceFunction() { + return serviceFunction; + } + + public void setServiceFunction(String serviceFunction) { + this.serviceFunction = serviceFunction; + } + + @Override + public String toString() { + return "ServiceMetadataDataDefinition{" + + "distributionStatus='" + distributionStatus + '\'' + + ", serviceType='" + serviceType + '\'' + + ", serviceRole='" + serviceRole + '\'' + + ", serviceFunction='" + serviceFunction + '\'' + + ", ecompGeneratedNaming=" + ecompGeneratedNaming + + ", namingPolicy='" + namingPolicy + '\'' + + ", environmentContext='" + environmentContext + '\'' + + ", instantiationType='" + instantiationType + '\'' + + '}'; + } @Override public int hashCode() { @@ -124,6 +152,7 @@ public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefiniti result = prime * result + ((namingPolicy == null) ? 0 : namingPolicy.hashCode()); result = prime * result + ((serviceType == null) ? 0 : serviceType.hashCode()); result = prime * result + ((serviceRole == null) ? 0 : serviceRole.hashCode()); + result = prime * result + ((serviceFunction == null) ? 0 : serviceFunction.hashCode()); result = prime * result + ((environmentContext == null) ? 0 : environmentContext.hashCode()); result = prime * result + ((instantiationType == null) ? 0 : instantiationType.hashCode()); return result; @@ -196,6 +225,12 @@ public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefiniti } else if (!instantiationType.equals(other.instantiationType)) { return false; } + if (serviceFunction == null){ + if (other.serviceFunction != null) { + return false; + } else if (!serviceFunction.equals(other.serviceFunction)) + return false; + } return super.equals(obj); } diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ComponentInstanceDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ComponentInstanceDataDefinition.java index 3790849ecf..4832e8b690 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ComponentInstanceDataDefinition.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ComponentInstanceDataDefinition.java @@ -1,334 +1,348 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.datatypes.elements; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.HashMap; -import java.util.stream.Collectors; -import org.apache.commons.collections.CollectionUtils; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.common.util.ValidationUtils; - -public class ComponentInstanceDataDefinition extends ToscaDataDefinition { - - public ComponentInstanceDataDefinition() { - setPropertyValueCounter(1); - setAttributeValueCounter(1); - setInputValueCounter(1); - setIsProxy(false); - } - - public ComponentInstanceDataDefinition(ComponentInstanceDataDefinition dataDefinition) { - setIcon(dataDefinition.getIcon()); - setUniqueId(dataDefinition.getUniqueId()); - setName(dataDefinition.getName()); - setComponentUid(dataDefinition.getComponentUid()); - setCreationTime(dataDefinition.getCreationTime()); - setModificationTime(dataDefinition.getModificationTime()); - setDescription(dataDefinition.getDescription()); - setPosX(dataDefinition.getPosX()); - setPosY(dataDefinition.getPosY()); - setPropertyValueCounter(dataDefinition.getPropertyValueCounter()); - setNormalizedName(dataDefinition.getNormalizedName()); - setOriginType(dataDefinition.getOriginType()); - setCustomizationUUID(dataDefinition.getCustomizationUUID()); - setComponentName(dataDefinition.getComponentName()); - setComponentVersion(dataDefinition.getComponentVersion()); - setToscaComponentName(dataDefinition.getToscaComponentName()); - setInvariantName(dataDefinition.getInvariantName()); - setSourceModelInvariant(dataDefinition.getSourceModelInvariant()); - setSourceModelName(dataDefinition.getSourceModelName()); - setSourceModelUuid(dataDefinition.getSourceModelUuid()); - setSourceModelUid(dataDefinition.getSourceModelUid()); - setIsProxy(dataDefinition.getIsProxy()); - setDirectives(dataDefinition.getDirectives()); - setOriginArchived(dataDefinition.isOriginArchived()); - setToscaArtifacts(dataDefinition.getToscaArtifacts()); - } - - public String getIcon() { - return (String) getToscaPresentationValue(JsonPresentationFields.CI_ICON); - } - - public void setIcon(String icon) { - setToscaPresentationValue(JsonPresentationFields.CI_ICON, icon); - } - - public String getUniqueId() { - return (String) getToscaPresentationValue(JsonPresentationFields.UNIQUE_ID); - } - - public void setUniqueId(String uniqueId) { - setToscaPresentationValue(JsonPresentationFields.UNIQUE_ID, uniqueId); - } - - public Long getCreationTime() { - return (Long) getToscaPresentationValue(JsonPresentationFields.CREATION_TIME); - } - - public void setCreationTime(Long creationTime) { - setToscaPresentationValue(JsonPresentationFields.CREATION_TIME, creationTime); - } - - public Long getModificationTime() { - return (Long) getToscaPresentationValue(JsonPresentationFields.MODIFICATION_TIME); - } - - public void setModificationTime(Long modificationTime) { - setToscaPresentationValue(JsonPresentationFields.MODIFICATION_TIME, modificationTime); - } - - public String getDescription() { - return (String) getToscaPresentationValue(JsonPresentationFields.DESCRIPTION); - } - - public void setDescription(String description) { - setToscaPresentationValue(JsonPresentationFields.DESCRIPTION, description); - } - - public String getPosX() { - return (String) getToscaPresentationValue(JsonPresentationFields.CI_POS_X); - } - - public void setPosX(String posX) { - setToscaPresentationValue(JsonPresentationFields.CI_POS_X, posX); - } - - public String getPosY() { - return (String) getToscaPresentationValue(JsonPresentationFields.CI_POS_Y); - } - - public void setPosY(String posY) { - setToscaPresentationValue(JsonPresentationFields.CI_POS_Y, posY); - } - - public String getComponentUid() { - return (String) getToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID); - } - - public void setComponentUid(String resourceUid) { - setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID, resourceUid); - } - - public String getName() { - return (String) getToscaPresentationValue(JsonPresentationFields.NAME); - } - - public void setName(String name) { - if (this.getInvariantName() == null && name != null) { - this.setInvariantName(ValidationUtils.normalizeComponentInstanceName(name)); - } - setToscaPresentationValue(JsonPresentationFields.NAME, name); - } - - public String getInvariantName() { - return (String) getToscaPresentationValue(JsonPresentationFields.CI_INVARIANT_NAME); - } - - public void setInvariantName(String invariantName) { - setToscaPresentationValue(JsonPresentationFields.CI_INVARIANT_NAME, invariantName); - } - - public Integer getPropertyValueCounter() { - return (Integer) getToscaPresentationValue(JsonPresentationFields.CI_PROP_VALUE_COUNTER); - } - - public void setPropertyValueCounter(Integer propertyValueCounter) { - setToscaPresentationValue(JsonPresentationFields.CI_PROP_VALUE_COUNTER, propertyValueCounter); - } - - public String getNormalizedName() { - return (String) getToscaPresentationValue(JsonPresentationFields.NORMALIZED_NAME); - } - - public void setNormalizedName(String normalizedName) { - setToscaPresentationValue(JsonPresentationFields.NORMALIZED_NAME, normalizedName); - } - - public OriginTypeEnum getOriginType() { - OriginTypeEnum originType = null; - String origType = (String) getToscaPresentationValue(JsonPresentationFields.CI_ORIGIN_TYPE); - if (origType != null && !origType.isEmpty()) { - - originType = OriginTypeEnum.findByValue(origType); - } - return originType; - } - - public void setOriginType(OriginTypeEnum originType) { - if (originType != null) { - setToscaPresentationValue(JsonPresentationFields.CI_ORIGIN_TYPE, originType.getValue()); - } - } - - public Integer getAttributeValueCounter() { - return (Integer) getToscaPresentationValue(JsonPresentationFields.CI_ATTR_VALUE_COUNTER); - } - - public void setAttributeValueCounter(Integer attributeValueCounter) { - setToscaPresentationValue(JsonPresentationFields.CI_ATTR_VALUE_COUNTER, attributeValueCounter); - } - - public Integer getInputValueCounter() { - return (Integer) getToscaPresentationValue(JsonPresentationFields.CI_INPUT_VALUE_COUNTER); - } - - public void setInputValueCounter(Integer inputValueCounter) { - setToscaPresentationValue(JsonPresentationFields.CI_INPUT_VALUE_COUNTER, inputValueCounter); - } - - public String getCustomizationUUID() { - return (String) getToscaPresentationValue(JsonPresentationFields.CUSTOMIZATION_UUID); - } - - public void setCustomizationUUID(String customizationUUID) { - setToscaPresentationValue(JsonPresentationFields.CUSTOMIZATION_UUID, customizationUUID); - } - - public String getComponentName() { - return (String) getToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_NAME); - } - - public void setComponentName(String resourceName) { - setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_NAME, resourceName); - } - - public String getComponentVersion() { - return (String) getToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_VERSION); - } - - public String getToscaComponentName() { - return (String) getToscaPresentationValue(JsonPresentationFields.CI_TOSCA_COMPONENT_NAME); - } - - public void setToscaComponentName(String toscaComponentName) { - setToscaPresentationValue(JsonPresentationFields.CI_TOSCA_COMPONENT_NAME, toscaComponentName); - } - - public void setComponentVersion(String resourceVersion) { - setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_VERSION, resourceVersion); - } - - public void setSourceModelUuid(String targetModelUuid) { - setToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UUID, targetModelUuid); - } - - public void setSourceModelUid(String targetModelUid) { - setToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UID, targetModelUid); - } - - public void setSourceModelName(String targetModelName) { - setToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_NAME, targetModelName); - } - - public void setSourceModelInvariant(String targetModelInvariant) { - setToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_INVARIANT, targetModelInvariant); - } - - public String getSourceModelUuid() { - return (String) getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UUID); - } - - public String getSourceModelUid() { - return (String) getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UID); - } - - public String getSourceModelName() { - return (String) getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_NAME); - } - - public String getSourceModelInvariant() { - return (String) getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_INVARIANT); - } - - public void setIsProxy(Boolean isProxy) { - if (isProxy == null) { - setToscaPresentationValue(JsonPresentationFields.CI_IS_PROXY, false); - } else { - setToscaPresentationValue(JsonPresentationFields.CI_IS_PROXY, isProxy); - } - } - - public Boolean getIsProxy() { - Boolean isProxy = (Boolean) getToscaPresentationValue(JsonPresentationFields.CI_IS_PROXY); - return (isProxy != null) ? isProxy : false; - } - - public void setOriginArchived(Boolean originArchived) { - if (originArchived == null) { - setToscaPresentationValue(JsonPresentationFields.CI_IS_ORIGIN_ARCHIVED, false); - } else { - setToscaPresentationValue(JsonPresentationFields.CI_IS_ORIGIN_ARCHIVED, originArchived); - } - } - - public List getDirectives() { - return (List) getToscaPresentationValue(JsonPresentationFields.CI_DIRECTIVES); - } - - public void setDirectives(List directives) { - if (directives == null) { - directives = new ArrayList<>(); - } - setToscaPresentationValue(JsonPresentationFields.CI_DIRECTIVES, directives); - } - - public Map getToscaArtifacts() { - return ( Map) getToscaPresentationValue(JsonPresentationFields.CI_ARTIFACTS); - } - - public void setToscaArtifacts(Map artifacts) { - if (artifacts == null){ - artifacts = new HashMap<>(); - } - setToscaPresentationValue(JsonPresentationFields.CI_ARTIFACTS, artifacts); - } - - public Boolean isOriginArchived() { - Boolean originArchived = (Boolean) getToscaPresentationValue(JsonPresentationFields.CI_IS_ORIGIN_ARCHIVED); - return (originArchived != null) ? originArchived : false; - } - - private String getDirectivesString() { - if (CollectionUtils.isEmpty(getDirectives())) { - return ""; - } - return getDirectives().stream().collect(Collectors.joining(",")); - } - - @Override - public String toString() { - return "ComponentInstanceDataDefinition [icon=" + getIcon() + ", uniqueId=" + getUniqueId() + ", name=" - + getName() + ", normalizedName=" + getNormalizedName() + ", componentUid=" + getComponentUid() - + ", creationTime=" + getCreationTime() + ", modificationTime=" + getModificationTime() - + ", description=" + getDescription() + ", posX=" + getPosX() + ", posY=" + getPosY() - + ", propertyValueCounter=" + getPropertyValueCounter() + ", attributeValueCounter=" - + getAttributeValueCounter() + ", inputValueCounter=" + getInputValueCounter() + ", originType=" - + getOriginType() + ", customizationUUID=" + getCustomizationUUID() + ", componentName=" - + getComponentName() + ", componentVersion=" + getComponentVersion() + ", toscaComponentName=" - + getToscaComponentName() + ", directives =" + getDirectivesString() + "]"; - } - -} +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.datatypes.elements; + +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.datatypes.enums.CreatedFrom; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.common.util.ValidationUtils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +public class ComponentInstanceDataDefinition extends ToscaDataDefinition { + + public ComponentInstanceDataDefinition() { + setPropertyValueCounter(1); + setAttributeValueCounter(1); + setInputValueCounter(1); + setIsProxy(false); + } + + public ComponentInstanceDataDefinition(ComponentInstanceDataDefinition dataDefinition) { + setIcon(dataDefinition.getIcon()); + setUniqueId(dataDefinition.getUniqueId()); + setName(dataDefinition.getName()); + setComponentUid(dataDefinition.getComponentUid()); + setCreationTime(dataDefinition.getCreationTime()); + setModificationTime(dataDefinition.getModificationTime()); + setDescription(dataDefinition.getDescription()); + setPosX(dataDefinition.getPosX()); + setPosY(dataDefinition.getPosY()); + setPropertyValueCounter(dataDefinition.getPropertyValueCounter()); + setNormalizedName(dataDefinition.getNormalizedName()); + setOriginType(dataDefinition.getOriginType()); + setCustomizationUUID(dataDefinition.getCustomizationUUID()); + setComponentName(dataDefinition.getComponentName()); + setComponentVersion(dataDefinition.getComponentVersion()); + setToscaComponentName(dataDefinition.getToscaComponentName()); + setInvariantName(dataDefinition.getInvariantName()); + setSourceModelInvariant(dataDefinition.getSourceModelInvariant()); + setSourceModelName(dataDefinition.getSourceModelName()); + setSourceModelUuid(dataDefinition.getSourceModelUuid()); + setSourceModelUid(dataDefinition.getSourceModelUid()); + setIsProxy(dataDefinition.getIsProxy()); + setDirectives(dataDefinition.getDirectives()); + setOriginArchived(dataDefinition.isOriginArchived()); + setToscaArtifacts(dataDefinition.getToscaArtifacts()); + } + + public String getIcon() { + return (String) getToscaPresentationValue(JsonPresentationFields.CI_ICON); + } + + public void setIcon(String icon) { + setToscaPresentationValue(JsonPresentationFields.CI_ICON, icon); + } + + public String getUniqueId() { + return (String) getToscaPresentationValue(JsonPresentationFields.UNIQUE_ID); + } + + public void setUniqueId(String uniqueId) { + setToscaPresentationValue(JsonPresentationFields.UNIQUE_ID, uniqueId); + } + + public Long getCreationTime() { + return (Long) getToscaPresentationValue(JsonPresentationFields.CREATION_TIME); + } + + public void setCreationTime(Long creationTime) { + setToscaPresentationValue(JsonPresentationFields.CREATION_TIME, creationTime); + } + + public Long getModificationTime() { + return (Long) getToscaPresentationValue(JsonPresentationFields.MODIFICATION_TIME); + } + + public void setModificationTime(Long modificationTime) { + setToscaPresentationValue(JsonPresentationFields.MODIFICATION_TIME, modificationTime); + } + + public CreatedFrom getCreatedFrom() { + String createdFrom = (String) getToscaPresentationValue(JsonPresentationFields.CREATED_FROM); + return Objects.nonNull(createdFrom) ? CreatedFrom.valueOf(createdFrom) : null; + } + + public void setCreatedFrom(CreatedFrom createdFrom) { + if (Objects.nonNull(createdFrom)){ + setToscaPresentationValue(JsonPresentationFields.CREATED_FROM, createdFrom.name()); + } + } + + public String getDescription() { + return (String) getToscaPresentationValue(JsonPresentationFields.DESCRIPTION); + } + + public void setDescription(String description) { + setToscaPresentationValue(JsonPresentationFields.DESCRIPTION, description); + } + + public String getPosX() { + return (String) getToscaPresentationValue(JsonPresentationFields.CI_POS_X); + } + + public void setPosX(String posX) { + setToscaPresentationValue(JsonPresentationFields.CI_POS_X, posX); + } + + public String getPosY() { + return (String) getToscaPresentationValue(JsonPresentationFields.CI_POS_Y); + } + + public void setPosY(String posY) { + setToscaPresentationValue(JsonPresentationFields.CI_POS_Y, posY); + } + + public String getComponentUid() { + return (String) getToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID); + } + + public void setComponentUid(String resourceUid) { + setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID, resourceUid); + } + + public String getName() { + return (String) getToscaPresentationValue(JsonPresentationFields.NAME); + } + + public void setName(String name) { + if (this.getInvariantName() == null && name != null) { + this.setInvariantName(ValidationUtils.normalizeComponentInstanceName(name)); + } + setToscaPresentationValue(JsonPresentationFields.NAME, name); + } + + public String getInvariantName() { + return (String) getToscaPresentationValue(JsonPresentationFields.CI_INVARIANT_NAME); + } + + public void setInvariantName(String invariantName) { + setToscaPresentationValue(JsonPresentationFields.CI_INVARIANT_NAME, invariantName); + } + + public Integer getPropertyValueCounter() { + return (Integer) getToscaPresentationValue(JsonPresentationFields.CI_PROP_VALUE_COUNTER); + } + + public void setPropertyValueCounter(Integer propertyValueCounter) { + setToscaPresentationValue(JsonPresentationFields.CI_PROP_VALUE_COUNTER, propertyValueCounter); + } + + public String getNormalizedName() { + return (String) getToscaPresentationValue(JsonPresentationFields.NORMALIZED_NAME); + } + + public void setNormalizedName(String normalizedName) { + setToscaPresentationValue(JsonPresentationFields.NORMALIZED_NAME, normalizedName); + } + + public OriginTypeEnum getOriginType() { + OriginTypeEnum originType = null; + String origType = (String) getToscaPresentationValue(JsonPresentationFields.CI_ORIGIN_TYPE); + if (origType != null && !origType.isEmpty()) { + + originType = OriginTypeEnum.findByValue(origType); + } + return originType; + } + + public void setOriginType(OriginTypeEnum originType) { + if (originType != null) { + setToscaPresentationValue(JsonPresentationFields.CI_ORIGIN_TYPE, originType.getValue()); + } + } + + public Integer getAttributeValueCounter() { + return (Integer) getToscaPresentationValue(JsonPresentationFields.CI_ATTR_VALUE_COUNTER); + } + + public void setAttributeValueCounter(Integer attributeValueCounter) { + setToscaPresentationValue(JsonPresentationFields.CI_ATTR_VALUE_COUNTER, attributeValueCounter); + } + + public Integer getInputValueCounter() { + return (Integer) getToscaPresentationValue(JsonPresentationFields.CI_INPUT_VALUE_COUNTER); + } + + public void setInputValueCounter(Integer inputValueCounter) { + setToscaPresentationValue(JsonPresentationFields.CI_INPUT_VALUE_COUNTER, inputValueCounter); + } + + public String getCustomizationUUID() { + return (String) getToscaPresentationValue(JsonPresentationFields.CUSTOMIZATION_UUID); + } + + public void setCustomizationUUID(String customizationUUID) { + setToscaPresentationValue(JsonPresentationFields.CUSTOMIZATION_UUID, customizationUUID); + } + + public String getComponentName() { + return (String) getToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_NAME); + } + + public void setComponentName(String resourceName) { + setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_NAME, resourceName); + } + + public String getComponentVersion() { + return (String) getToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_VERSION); + } + + public String getToscaComponentName() { + return (String) getToscaPresentationValue(JsonPresentationFields.CI_TOSCA_COMPONENT_NAME); + } + + public void setToscaComponentName(String toscaComponentName) { + setToscaPresentationValue(JsonPresentationFields.CI_TOSCA_COMPONENT_NAME, toscaComponentName); + } + + public void setComponentVersion(String resourceVersion) { + setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_VERSION, resourceVersion); + } + + public void setSourceModelUuid(String targetModelUuid) { + setToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UUID, targetModelUuid); + } + + public void setSourceModelUid(String targetModelUid) { + setToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UID, targetModelUid); + } + + public void setSourceModelName(String targetModelName) { + setToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_NAME, targetModelName); + } + + public void setSourceModelInvariant(String targetModelInvariant) { + setToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_INVARIANT, targetModelInvariant); + } + + public String getSourceModelUuid() { + return (String) getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UUID); + } + + public String getSourceModelUid() { + return (String) getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UID); + } + + public String getSourceModelName() { + return (String) getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_NAME); + } + + public String getSourceModelInvariant() { + return (String) getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_INVARIANT); + } + + public void setIsProxy(Boolean isProxy) { + if (isProxy == null) { + setToscaPresentationValue(JsonPresentationFields.CI_IS_PROXY, false); + } else { + setToscaPresentationValue(JsonPresentationFields.CI_IS_PROXY, isProxy); + } + } + + public Boolean getIsProxy() { + Boolean isProxy = (Boolean) getToscaPresentationValue(JsonPresentationFields.CI_IS_PROXY); + return (isProxy != null) ? isProxy : false; + } + + public void setOriginArchived(Boolean originArchived) { + if (originArchived == null) { + setToscaPresentationValue(JsonPresentationFields.CI_IS_ORIGIN_ARCHIVED, false); + } else { + setToscaPresentationValue(JsonPresentationFields.CI_IS_ORIGIN_ARCHIVED, originArchived); + } + } + + public List getDirectives() { + return (List) getToscaPresentationValue(JsonPresentationFields.CI_DIRECTIVES); + } + + public void setDirectives(List directives) { + if (directives == null) { + directives = new ArrayList<>(); + } + setToscaPresentationValue(JsonPresentationFields.CI_DIRECTIVES, directives); + } + + public Map getToscaArtifacts() { + return ( Map) getToscaPresentationValue(JsonPresentationFields.CI_ARTIFACTS); + } + + public void setToscaArtifacts(Map artifacts) { + if (artifacts == null){ + artifacts = new HashMap<>(); + } + setToscaPresentationValue(JsonPresentationFields.CI_ARTIFACTS, artifacts); + } + + public Boolean isOriginArchived() { + Boolean originArchived = (Boolean) getToscaPresentationValue(JsonPresentationFields.CI_IS_ORIGIN_ARCHIVED); + return (originArchived != null) ? originArchived : false; + } + + private String getDirectivesString() { + if (CollectionUtils.isEmpty(getDirectives())) { + return ""; + } + return getDirectives().stream().collect(Collectors.joining(",")); + } + + @Override + public String toString() { + return "ComponentInstanceDataDefinition [icon=" + getIcon() + ", uniqueId=" + getUniqueId() + ", name=" + + getName() + ", normalizedName=" + getNormalizedName() + ", componentUid=" + getComponentUid() + + ", creationTime=" + getCreationTime() + ", modificationTime=" + getModificationTime() + + ", description=" + getDescription() + ", posX=" + getPosX() + ", posY=" + getPosY() + + ", propertyValueCounter=" + getPropertyValueCounter() + ", attributeValueCounter=" + + getAttributeValueCounter() + ", inputValueCounter=" + getInputValueCounter() + ", originType=" + + getOriginType() + ", customizationUUID=" + getCustomizationUUID() + ", componentName=" + + getComponentName() + ", componentVersion=" + getComponentVersion() + ", toscaComponentName=" + + getToscaComponentName() + ", directives =" + getDirectivesString() + "]"; + } + +} diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupDataDefinition.java index bf8b868847..ad61426583 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupDataDefinition.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupDataDefinition.java @@ -20,6 +20,7 @@ package org.openecomp.sdc.be.datatypes.elements; +import com.fasterxml.jackson.annotation.JsonInclude; import org.openecomp.sdc.be.datatypes.enums.CreatedFrom; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; @@ -33,9 +34,9 @@ import static java.util.Collections.emptyMap; public class GroupDataDefinition extends ToscaDataDefinition { - + @JsonInclude private String typeUid; - + @JsonInclude private Integer propertyValueCounter = 0; public GroupDataDefinition() { diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ProductMetadataDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ProductMetadataDataDefinition.java index 97107dbbf2..2d8350b9ef 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ProductMetadataDataDefinition.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ProductMetadataDataDefinition.java @@ -21,6 +21,7 @@ package org.openecomp.sdc.be.datatypes.elements; import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFieldsExtractor; import java.util.ArrayList; import java.util.List; @@ -39,6 +40,10 @@ public class ProductMetadataDataDefinition extends ComponentMetadataDataDefiniti public ProductMetadataDataDefinition(ProductMetadataDataDefinition other) { super(other); + } + + public ProductMetadataDataDefinition(JsonPresentationFieldsExtractor extractor){ + super(extractor); } public Boolean getIsActive() { diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyDataDefinition.java index af29a2f424..c138617f42 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyDataDefinition.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyDataDefinition.java @@ -79,13 +79,14 @@ public class PropertyDataDefinition extends ToscaDataDefinition { private List getPolicyValues; + private List propertyConstraints; + public PropertyDataDefinition() { super(); } public PropertyDataDefinition(Map pr) { super(pr); - } public PropertyDataDefinition(PropertyDataDefinition propertyDataDefinition) { @@ -93,6 +94,7 @@ public class PropertyDataDefinition extends ToscaDataDefinition { this.setUniqueId(propertyDataDefinition.getUniqueId()); this.setRequired(propertyDataDefinition.isRequired()); this.setDefaultValue(propertyDataDefinition.getDefaultValue()); + this.setDefinition(propertyDataDefinition.getDefinition()); this.setDescription(propertyDataDefinition.getDescription()); this.setSchema(propertyDataDefinition.getSchema()); this.setPassword(propertyDataDefinition.isPassword()); @@ -117,6 +119,9 @@ public class PropertyDataDefinition extends ToscaDataDefinition { if (isNotEmpty(propertyDataDefinition.annotations)) { this.setAnnotations(propertyDataDefinition.annotations); } + if(isNotEmpty(propertyDataDefinition.getPropertyConstraints())){ + setPropertyConstraints(new ArrayList<>(propertyDataDefinition.getPropertyConstraints())); + } this.setIsDeclaredListInput(propertyDataDefinition.getIsDeclaredListInput()); } @@ -169,6 +174,10 @@ public class PropertyDataDefinition extends ToscaDataDefinition { this.definition = definition; } + public boolean getDefinition() { + return definition; + } + public String getType() { return type; } @@ -575,4 +584,11 @@ public class PropertyDataDefinition extends ToscaDataDefinition { return (List) getToscaPresentationValue(JsonPresentationFields.ANNOTATIONS); } + public List getPropertyConstraints() { + return propertyConstraints; + } + + public void setPropertyConstraints(List constraints) { + this.propertyConstraints = constraints; + } } diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/GraphPropertyEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/GraphPropertyEnum.java index 058bcac046..09e1de6c7b 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/GraphPropertyEnum.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/GraphPropertyEnum.java @@ -55,10 +55,14 @@ public enum GraphPropertyEnum { IS_ARCHIVED("isArchived", Boolean.class, false, true), IS_VSP_ARCHIVED("isVspArchived", Boolean.class, false, true), ARCHIVE_TIME("archiveTime", Long.class, false, true), + PREV_CATALOG_UPDATE_TIME ("previousUpdateTime", Long.class, false, true), + CURRENT_CATALOG_UPDATE_TIME ("currentUpdateTime", Long.class, false, true), //Healing HEALING_VERSION("healVersion", Integer.class, false, true); + + private String property; private Class clazz; private boolean unique; diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFields.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFields.java index 3a824d52f8..b84baff861 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFields.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFields.java @@ -58,6 +58,7 @@ public enum JsonPresentationFields { DISTRIBUTION_STATUS("distributionStatus", GraphPropertyEnum.DISTRIBUTION_STATUS), DERIVED_FROM_GENERIC_TYPE("derivedFromGenericType", null), DERIVED_FROM_GENERIC_VERSION("derivedFromGenericVersion", null), + SERVICE_FUNCTION("serviceFunction", null), ////Inputs ANNOTATIONS("annotations", null), @@ -221,9 +222,18 @@ public enum JsonPresentationFields { IS_VSP_ARCHIVED("isVspArchived", GraphPropertyEnum.IS_VSP_ARCHIVED), CI_IS_ORIGIN_ARCHIVED("isOriginArchived", null), - //Interface Operation - IO_WORKFLOW_ID("workflowId", null), - IO_WORKFLOW_VERSION_ID("workflowVersionId", null), + //Interface Operation + IO_OPERATION_TYPE("operationType",null), + IO_INPUT_PARAMETERS("inputParams",null), + IO_OUTPUT_PARAMETERS("outputParams",null), + IO_PARAM_NAME("paramName", null), + IO_PARAM_ID("paramId", null), + IO_NAME("name", null), + IO_MANDATORY("mandatory", null), + IO_TYPE("type", null), + IO_PROPERTY("property", null), + IO_WORKFLOW_ID("workflowId", null), + IO_WORKFLOW_VERSION_ID("workflowVersionId", null), IO_WORKFLOW_ASSOCIATION_TYPE("workflowAssociationType", null), //Interface diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFieldsExtractor.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFieldsExtractor.java new file mode 100644 index 0000000000..5f20c58a84 --- /dev/null +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFieldsExtractor.java @@ -0,0 +1,170 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * Modifications copyright (c) 2019 Nokia + * ================================================================================ + */ + +package org.openecomp.sdc.be.datatypes.enums; + +import java.util.List; +import java.util.Map; + +public class JsonPresentationFieldsExtractor { + + private Map properties; + + public JsonPresentationFieldsExtractor(Map properties) { + this.properties = properties; + } + + public String getUniqueId() { + return (String) properties.get(JsonPresentationFields.UNIQUE_ID.getPresentation()); + } + + public String getName() { + return (String) properties.get(JsonPresentationFields.NAME.getPresentation()); + } + + public String getVersion() { + return (String) properties.get(JsonPresentationFields.VERSION.getPresentation()); + } + + public Boolean isHighestVersion() { + return (Boolean) properties.get(JsonPresentationFields.HIGHEST_VERSION.getPresentation()); + } + + public Long getCreationDate() { + return (Long) properties.get(JsonPresentationFields.CREATION_DATE.getPresentation()); + } + + public Long getLastUpdateDate() { + return (Long) properties.get(JsonPresentationFields.LAST_UPDATE_DATE.getPresentation()); + } + + public String getDescription() { + return (String) properties.get(JsonPresentationFields.DESCRIPTION.getPresentation()); + } + + public String getState() { + return (String) properties.get(JsonPresentationFields.LIFECYCLE_STATE.getPresentation()); + } + + @SuppressWarnings("unchecked") + public List getTags() { + return (List) properties.get(JsonPresentationFields.TAGS.getPresentation()); + } + + public String getIcon() { + return (String) properties.get(JsonPresentationFields.ICON.getPresentation()); + } + + public String getContactId() { + return (String) properties.get(JsonPresentationFields.CONTACT_ID.getPresentation()); + } + + public String getUUID() { + return (String) properties.get(JsonPresentationFields.UUID.getPresentation()); + } + + public String getNormalizedName() { + return (String) properties.get(JsonPresentationFields.NORMALIZED_NAME.getPresentation()); + } + + public String getSystemName() { + return (String) properties.get(JsonPresentationFields.SYSTEM_NAME.getPresentation()); + } + + public Boolean isDeleted() { + return (Boolean) properties.get(JsonPresentationFields.IS_DELETED.getPresentation()); + } + + public String getProjectCode() { + return (String) properties.get(JsonPresentationFields.PROJECT_CODE.getPresentation()); + } + + public String getCsarUuid() { + return (String) properties.get(JsonPresentationFields.CSAR_UUID.getPresentation()); + } + + public String getCsarVersion() { + return (String) properties.get(JsonPresentationFields.CSAR_VERSION.getPresentation()); + } + + public String getImportedToscaChecksum() { + return (String) properties.get(JsonPresentationFields.IMPORTED_TOSCA_CHECKSUM.getPresentation()); + } + + public String getInvariantUuid() { + return (String) properties.get(JsonPresentationFields.INVARIANT_UUID.getPresentation()); + } + + public Boolean isArchived() { + return (Boolean) properties.get(JsonPresentationFields.IS_ARCHIVED.getPresentation()); + } + + public Boolean isVspArchived() { + return (Boolean) properties.get(JsonPresentationFields.IS_VSP_ARCHIVED.getPresentation()); + } + + public Long getArchiveTime() { + Object archiveTimeObject = properties.get(JsonPresentationFields.ARCHIVE_TIME.getPresentation()); + if (archiveTimeObject instanceof Integer) { + return Long.valueOf((Integer) archiveTimeObject); + } else { + return (Long) archiveTimeObject; + } + } + + public String getVendorName() { + return (String) properties.get(JsonPresentationFields.VENDOR_NAME.getPresentation()); + } + + public String getVendorRelease() { + return (String) properties.get(JsonPresentationFields.VENDOR_RELEASE.getPresentation()); + } + + public String getResourceVendorModelNumber() { + return (String) properties.get(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER.getPresentation()); + } + + public Boolean isAbstract() { + return (Boolean) properties.get(JsonPresentationFields.IS_ABSTRACT.getPresentation()); + } + + public ResourceTypeEnum getResourceType() { + return ResourceTypeEnum.valueOf((String)properties.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation())); + } + + public String getToscaResourceName() { + return (String) properties.get(JsonPresentationFields.TOSCA_RESOURCE_NAME.getPresentation()); + } + + public String getServiceType() { + return (String) properties.get(JsonPresentationFields.SERVICE_TYPE.getPresentation()); + } + + public String getServiceRole() { + return (String) properties.get(JsonPresentationFields.SERVICE_ROLE.getPresentation()); + } + + public String getServiceFunction() { + return (String) properties.get(JsonPresentationFields.SERVICE_FUNCTION.getPresentation()); + } + +} diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/OriginTypeEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/OriginTypeEnum.java index c7c576d95a..48394013de 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/OriginTypeEnum.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/OriginTypeEnum.java @@ -33,12 +33,14 @@ public enum OriginTypeEnum { private String displayValue; private String instanceType; private ComponentTypeEnum componentType; + private boolean isAtomicType; OriginTypeEnum(String value, String displayValue, String instanceType, ComponentTypeEnum componentType, boolean isAtomicType) { this.value = value; this.displayValue = displayValue; this.instanceType = instanceType; this.componentType = componentType; + this.isAtomicType = isAtomicType; } public String getValue() { @@ -57,6 +59,10 @@ public enum OriginTypeEnum { return componentType; } + public boolean isAtomicType() { + return isAtomicType; + } + public static OriginTypeEnum findByValue(String value) { OriginTypeEnum ret = null; for (OriginTypeEnum curr : OriginTypeEnum.values()) { @@ -67,4 +73,5 @@ public enum OriginTypeEnum { } return ret; } + } diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/PortMirroringEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/PortMirroringEnum.java new file mode 100644 index 0000000000..305ae79821 --- /dev/null +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/PortMirroringEnum.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * Modifications copyright (c) 2019 Nokia + * ================================================================================ + */ + +package org.openecomp.sdc.be.datatypes.enums; + +public enum PortMirroringEnum { + CISCO_VENDOR_NAME("CISCO"), + CISCO_VENDOR_MODEL_NUMBER("4500x"); + + private String value; + + public String getValue() { + return value; + } + + PortMirroringEnum(String value) { + this.value = value; + } +} diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/PromoteVersionEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/PromoteVersionEnum.java new file mode 100644 index 0000000000..3ad423927a --- /dev/null +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/PromoteVersionEnum.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * Modifications copyright (c) 2019 Nokia + * ================================================================================ + */ + +package org.openecomp.sdc.be.datatypes.enums; + +public enum PromoteVersionEnum { + + NONE, + MINOR, + MAJOR + +} diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ResourceTypeEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ResourceTypeEnum.java index 21d4e5ca53..bd32ace9e5 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ResourceTypeEnum.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ResourceTypeEnum.java @@ -30,8 +30,8 @@ public enum ResourceTypeEnum { CVFC("CVFC"/* Complex Virtual Function Component*/, false), VL("VL"/* (Virtual Link)"*/, true), VFCMT("VFCMT"/* (VFC Monitoring Template)"*/, true), - Configuration("Configuration ()", true), - ServiceProxy("ServiceProxy ()", true), + Configuration("Configuration", true), + ServiceProxy("ServiceProxy", true), ABSTRACT("Abstract (Generic VFC/VF/PNF/Service Type)", true); private String value; diff --git a/common-be/src/test/java/org/openecomp/sdc/be/config/NonManoConfigurationManagerTest.java b/common-be/src/test/java/org/openecomp/sdc/be/config/NonManoConfigurationManagerTest.java index bbe8623ed8..3c51778fb1 100644 --- a/common-be/src/test/java/org/openecomp/sdc/be/config/NonManoConfigurationManagerTest.java +++ b/common-be/src/test/java/org/openecomp/sdc/be/config/NonManoConfigurationManagerTest.java @@ -19,14 +19,14 @@ package org.openecomp.sdc.be.config; +import org.junit.Test; + import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.Matchers.anEmptyMap; import static org.junit.Assert.assertThat; -import org.junit.Test; - public class NonManoConfigurationManagerTest { @Test diff --git a/common-be/src/test/java/org/openecomp/sdc/be/csar/pnf/SoftwareInformationArtifactYamlParserTest.java b/common-be/src/test/java/org/openecomp/sdc/be/csar/pnf/SoftwareInformationArtifactYamlParserTest.java index b866fd55db..bc49f2d417 100644 --- a/common-be/src/test/java/org/openecomp/sdc/be/csar/pnf/SoftwareInformationArtifactYamlParserTest.java +++ b/common-be/src/test/java/org/openecomp/sdc/be/csar/pnf/SoftwareInformationArtifactYamlParserTest.java @@ -19,16 +19,17 @@ package org.openecomp.sdc.be.csar.pnf; +import org.junit.Test; +import org.openecomp.sdc.be.test.util.TestResourcesHandler; + +import java.io.IOException; +import java.util.Optional; + import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItems; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; -import java.io.IOException; -import java.util.Optional; -import org.junit.Test; -import org.openecomp.sdc.be.test.util.TestResourcesHandler; - public class SoftwareInformationArtifactYamlParserTest { @Test diff --git a/common-be/src/test/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinitionTest.java b/common-be/src/test/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinitionTest.java index 3842f0a00e..77b6871c92 100644 --- a/common-be/src/test/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinitionTest.java +++ b/common-be/src/test/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinitionTest.java @@ -21,12 +21,34 @@ package org.openecomp.sdc.be.datatypes.components; import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.utils.DummyConfigurationManager; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class ServiceMetadataDataDefinitionTest { + private Configuration.EnvironmentContext environmentContext = mock(Configuration.EnvironmentContext.class); + private static final String DEFAULT_ENVIRONMENT = "General_Revenue-Bearing"; + @BeforeClass + public static void setup() { + new DummyConfigurationManager(); + } + + @Before + public void beforeTest() { + when(environmentContext.getDefaultValue()).thenReturn(DEFAULT_ENVIRONMENT); + when(ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext()) + .thenReturn(environmentContext); + } + private ServiceMetadataDataDefinition createTestSubject() { return new ServiceMetadataDataDefinition(); } diff --git a/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/CompositionDataDefinitionTest.java b/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/CompositionDataDefinitionTest.java index 390d1004d3..df6a10c293 100644 --- a/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/CompositionDataDefinitionTest.java +++ b/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/CompositionDataDefinitionTest.java @@ -20,10 +20,10 @@ package org.openecomp.sdc.be.datatypes.elements; -import java.util.Map; - import org.junit.Test; +import java.util.Map; + public class CompositionDataDefinitionTest { diff --git a/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/ConsumerDataDefinitionTest.java b/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/ConsumerDataDefinitionTest.java index ddcb32f87a..b8b55369c5 100644 --- a/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/ConsumerDataDefinitionTest.java +++ b/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/ConsumerDataDefinitionTest.java @@ -19,13 +19,12 @@ */ package org.openecomp.sdc.be.datatypes.elements; -import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters; -import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSettersExcluding; -import static org.junit.Assert.assertThat; - import org.junit.Assert; import org.junit.Test; +import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSettersExcluding; +import static org.junit.Assert.assertThat; + public class ConsumerDataDefinitionTest { private ConsumerDataDefinition createTestSubject() { diff --git a/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/MapCapabilityPropertyTest.java b/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/MapCapabilityPropertyTest.java index 14d6504d7a..b5f04de358 100644 --- a/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/MapCapabilityPropertyTest.java +++ b/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/MapCapabilityPropertyTest.java @@ -20,11 +20,11 @@ package org.openecomp.sdc.be.datatypes.elements; +import org.junit.Test; + import java.util.HashMap; import java.util.Map; -import org.junit.Test; - public class MapCapabilityPropertyTest { private MapCapabilityProperty createTestSubject() { diff --git a/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/MapListRequirementDataDefinitionTest.java b/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/MapListRequirementDataDefinitionTest.java index 86b4c27805..4001599277 100644 --- a/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/MapListRequirementDataDefinitionTest.java +++ b/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/MapListRequirementDataDefinitionTest.java @@ -20,11 +20,11 @@ package org.openecomp.sdc.be.datatypes.elements; +import org.junit.Test; + import java.util.HashMap; import java.util.Map; -import org.junit.Test; - public class MapListRequirementDataDefinitionTest { diff --git a/common-be/src/test/java/org/openecomp/sdc/be/test/util/TestResourcesHandler.java b/common-be/src/test/java/org/openecomp/sdc/be/test/util/TestResourcesHandler.java index 3aba23692f..2e3b906a5d 100644 --- a/common-be/src/test/java/org/openecomp/sdc/be/test/util/TestResourcesHandler.java +++ b/common-be/src/test/java/org/openecomp/sdc/be/test/util/TestResourcesHandler.java @@ -19,15 +19,16 @@ package org.openecomp.sdc.be.test.util; -import static org.junit.Assert.fail; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Path; -import org.apache.commons.io.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import static org.junit.Assert.fail; /** * Util class for handling test resources. diff --git a/common-be/src/test/java/org/openecomp/sdc/be/utils/CommonBeUtilsTest.java b/common-be/src/test/java/org/openecomp/sdc/be/utils/CommonBeUtilsTest.java index 7670913163..6f8ffe529f 100644 --- a/common-be/src/test/java/org/openecomp/sdc/be/utils/CommonBeUtilsTest.java +++ b/common-be/src/test/java/org/openecomp/sdc/be/utils/CommonBeUtilsTest.java @@ -22,9 +22,9 @@ package org.openecomp.sdc.be.utils; -import static org.junit.Assert.assertEquals; import org.junit.Test; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; diff --git a/common-be/src/test/java/org/openecomp/sdc/be/utils/DummyConfigurationManager.java b/common-be/src/test/java/org/openecomp/sdc/be/utils/DummyConfigurationManager.java new file mode 100644 index 0000000000..2f8c81cf0c --- /dev/null +++ b/common-be/src/test/java/org/openecomp/sdc/be/utils/DummyConfigurationManager.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * Modifications copyright (c) 2019 Nokia + * ================================================================================ + */ + +package org.openecomp.sdc.be.utils; + +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.common.api.ConfigurationListener; +import org.openecomp.sdc.common.api.ConfigurationSource; + +import static org.mockito.Mockito.mock; + +public class DummyConfigurationManager { + + private DistributionEngineConfiguration distributionConfigurationMock = mock(DistributionEngineConfiguration.class); + private Configuration configurationMock = mock(Configuration.class); + + public DummyConfigurationManager() { + new ConfigurationManager(new DummyConfigurationSource()); + } + + public class DummyConfigurationSource implements ConfigurationSource { + + @SuppressWarnings("unchecked") + @Override + public T getAndWatchConfiguration(Class className, ConfigurationListener configurationListener) { + if (className.equals(DistributionEngineConfiguration.class)) { + return (T) distributionConfigurationMock; + } + if (className.equals(Configuration.class)) { + return (T) configurationMock; + } + return null; + } + + @Override + public void addWatchConfiguration(Class className, ConfigurationListener configurationListener) { + + } + } + +} diff --git a/common-be/src/test/java/org/openecomp/sdc/be/utils/PropertyDefinitionUtilsTest.java b/common-be/src/test/java/org/openecomp/sdc/be/utils/PropertyDefinitionUtilsTest.java index b9f11d32a7..a4d5eed056 100644 --- a/common-be/src/test/java/org/openecomp/sdc/be/utils/PropertyDefinitionUtilsTest.java +++ b/common-be/src/test/java/org/openecomp/sdc/be/utils/PropertyDefinitionUtilsTest.java @@ -19,17 +19,18 @@ */ package org.openecomp.sdc.be.utils; -import static java.util.Collections.emptyMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; + +import static java.util.Collections.emptyMap; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; public class PropertyDefinitionUtilsTest { diff --git a/common-be/src/test/java/org/openecomp/sdc/be/utils/TypeUtilsTest.java b/common-be/src/test/java/org/openecomp/sdc/be/utils/TypeUtilsTest.java index fc5cea4b82..2f6ddf92e8 100644 --- a/common-be/src/test/java/org/openecomp/sdc/be/utils/TypeUtilsTest.java +++ b/common-be/src/test/java/org/openecomp/sdc/be/utils/TypeUtilsTest.java @@ -21,15 +21,16 @@ */ package org.openecomp.sdc.be.utils; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Consumer; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; + @RunWith(MockitoJUnitRunner.class) public class TypeUtilsTest { diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/pom.xml index 7c4e1b1ade..5fe1eeea38 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/pom.xml +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/pom.xml @@ -1,70 +1,87 @@ - 4.0.0 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - application-config-rest-services + application-config-rest-services - - org.openecomp.sdc - application-config-rest - 1.6.0-SNAPSHOT - + + org.openecomp.sdc + application-config-rest + 1.6.0-SNAPSHOT + - + + 2.22.2 + + + + + + io.swagger.core.v3 + swagger-annotations + ${swagger.version} + + + javax.ws.rs + javax.ws.rs-api + ${ws.rs.version} + + + org.springframework + spring-context + ${spring.framework.version} + + + javax.inject + javax.inject + ${javax.inject.version} + + + org.openecomp.sdc + openecomp-sdc-application-config-manager + ${project.version} + + + org.openecomp.sdc + application-config-rest-types + ${project.version} + + + org.openecomp.sdc + openecomp-sdc-common-rest + ${project.version} + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf.version} + + + junit + junit + test + + + org.springframework + spring-web + test + ${spring.framework.version} + + + org.glassfish.jersey.core + jersey-common + ${jersey-common.version} + test + + + org.glassfish.jersey.core + jersey-server + ${jersey-common.version} + test + + - - io.swagger.core.v3 - swagger-annotations - ${swagger.version} - - - javax.ws.rs - javax.ws.rs-api - ${ws.rs.version} - - - org.springframework - spring-context - ${spring.framework.version} - - - javax.inject - javax.inject - ${javax.inject.version} - - - org.openecomp.sdc - openecomp-sdc-application-config-manager - ${project.version} - - - org.openecomp.sdc - application-config-rest-types - ${project.version} - - - org.openecomp.sdc - openecomp-sdc-common-rest - ${project.version} - - - - org.apache.cxf - cxf-rt-frontend-jaxrs - ${cxf.version} - - - junit - junit - test - - - org.springframework - spring-web - test - ${spring.framework.version} - - diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/pom.xml index 9419c37ced..e1bdeb09c1 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/pom.xml +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/pom.xml @@ -16,82 +16,81 @@ --> - 4.0.0 - openecomp-sdc-common-rest - openecomp-sdc-common-rest - - org.openecomp.sdc - openecomp-sdc-rest-webapp - 1.6.0-SNAPSHOT - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + openecomp-sdc-common-rest + openecomp-sdc-common-rest + + org.openecomp.sdc + openecomp-sdc-rest-webapp + 1.6.0-SNAPSHOT + - - 2.22.2 - + + - - - org.openecomp.sdc - openecomp-sdc-logging-core - ${project.version} - runtime - - - org.openecomp.sdc.core - openecomp-utilities-lib - ${project.version} - - - org.openecomp.sdc.core - openecomp-common-lib - ${project.version} - - - org.hibernate - hibernate-validator - ${hibernate.validator.version} - - - javax.ws.rs - javax.ws.rs-api - ${ws.rs.version} - - - - io.swagger.core.v3 - swagger-core - ${swagger.version} - compile - - - org.openecomp.sdc.core - openecomp-session-lib - ${project.version} - - - javax.servlet - servlet-api - ${javax.servlet.version} - provided - - - junit - junit - test - - - org.glassfish.jersey.core - jersey-common - ${jersey-common.version} - test - - - org.mockito - mockito-core - test - - + + + org.openecomp.sdc + openecomp-sdc-logging-core + ${project.version} + runtime + + + org.openecomp.sdc.core + openecomp-utilities-lib + ${project.version} + + + org.openecomp.sdc.core + openecomp-common-lib + ${project.version} + + + org.hibernate + hibernate-validator + ${hibernate.validator.version} + + + javax.ws.rs + javax.ws.rs-api + ${ws.rs.version} + + + + io.swagger.core.v3 + swagger-core + ${swagger.version} + compile + + + org.openecomp.sdc.core + openecomp-session-lib + ${project.version} + + + javax.servlet + servlet-api + ${javax.servlet.version} + provided + + + junit + junit + test + + + org.glassfish.jersey.core + jersey-common + ${jersey-bom.version} + test + + + org.mockito + mockito-core + test + + diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/unique-type-rest/unique-type-rest-services/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/unique-type-rest/unique-type-rest-services/pom.xml index e27d22e96d..f7040ab9d8 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/unique-type-rest/unique-type-rest-services/pom.xml +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/unique-type-rest/unique-type-rest-services/pom.xml @@ -1,72 +1,69 @@ - 4.0.0 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - - org.openecomp.sdc - unique-type-rest - 1.6.0-SNAPSHOT - + + org.openecomp.sdc + unique-type-rest + 1.6.0-SNAPSHOT + - unique-type-rest-services + unique-type-rest-services - - 2.22.2 - + + + + + org.openecomp.sdc + unique-type-rest-types + ${project.version} + + + org.openecomp.sdc + openecomp-sdc-common-rest + ${project.version} + + + org.openecomp.sdc.core + openecomp-nosqldb-api + ${project.version} + + + javax.inject + javax.inject + ${javax.inject.version} + + + javax.ws.rs + javax.ws.rs-api + ${ws.rs.version} + + + org.springframework + spring-context + ${spring.framework.version} + - - - org.openecomp.sdc - unique-type-rest-types - ${project.version} - - - org.openecomp.sdc - openecomp-sdc-common-rest - ${project.version} - - - org.openecomp.sdc.core - openecomp-nosqldb-api - ${project.version} - - - javax.inject - javax.inject - ${javax.inject.version} - - - javax.ws.rs - javax.ws.rs-api - ${ws.rs.version} - - - org.springframework - spring-context - ${spring.framework.version} - - - - junit - junit - ${junit.version} - test - - - org.mockito - mockito-core - test - - - org.glassfish.jersey.core - jersey-common - ${jersey-common.version} - test - - - + + junit + junit + ${junit.version} + test + + + org.mockito + mockito-core + test + + + org.glassfish.jersey.core + jersey-common + ${jersey-bom.version} + test + + \ No newline at end of file diff --git a/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/logback.xml b/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/logback.xml index 7044d345c5..2098836dd3 100644 --- a/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/logback.xml +++ b/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/logback.xml @@ -1,315 +1,253 @@ - - - - - - - - - - - - - - - - - - - - - - ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/all.log - - - - ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/all.log.%i - - 1 - 10 - - - - 20MB - - - ${default-log-pattern} - - - - - - - - - - - - ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/error.log - - - - - - AUDIT_MARKER - - NEUTRAL - DENY - - - - - - TRANSACTION_MARKER - - NEUTRAL - DENY - - - - - INFO - - - - ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/error.log.%i - - 1 - 10 - - - - 20MB - - - ${error-log-pattern} - - - - - - ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/debug.log - - - - - - - TRANSACTION_MARKER - - NEUTRAL - DENY - - - - - - - e.level.toInt() <= DEBUG.toInt() - - - DENY - - ACCEPT - - - - ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/debug.log.%i - - 1 - 10 - - - - 20MB - - - ${debug-log-pattern} - - - - - - - ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/debug_by_package.log - - - - - - - TRANSACTION_MARKER - - NEUTRAL - DENY - - - - - - - e.level.toInt() <= DEBUG.toInt() - - - DENY - NEUTRAL - - - - ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/debug_by_package.log.%i - - 1 - 10 - - - - 20MB - - - ${debug-log-pattern} - - - - - - - ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/audit.log - - - - - - AUDIT_MARKER - AUDIT - - DENY - ACCEPT - - - - ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/audit.log.%i - - 1 - 10 - - - - 20MB - - - ${audit-log-pattern} - - - - - - - ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/metrics.log - - - - - - METRICS - - DENY - ACCEPT - - - - ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/metrics.log.%i - - 1 - 10 - - - - 20MB - - - ${metric-log-pattern} - - - - - - - ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/transaction.log - - - - - - TRANSACTION_MARKER - - DENY - ACCEPT - - - - ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/transaction.log.%i - - 1 - 10 - - - - 20MB - - - ${default-log-pattern} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/all.log + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/all.log.%i + + 1 + 10 + + + + 20MB + + + + ${all-log-pattern} + + + + + + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/debug.log + + + + + ENTRY + EXIT + INVOKE + INVOKE-RETURN + INVOKE-SYNCHRONOUS + + NEUTRAL + DENY + + + + + + + e.level.toInt() <= INFO.toInt() + + + DENY + ACCEPT + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/debug.log.%i + + 1 + 10 + + + + 20MB + + + + ${debug-log-pattern} + + + + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/error.log + + + + WARN + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/error.log.%i + + 1 + 10 + + + + 20MB + + + + ${error-log-pattern} + + + + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/audit.log + + + + + ENTRY + EXIT + + DENY + ACCEPT + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/audit.log.%i + + 1 + 10 + + + + 20MB + + + + ${audit-log-pattern} + + + + + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/metrics.log + + + + + + INVOKE + INVOKE-RETURN + INVOKE-SYNCHRONOUS + + DENY + ACCEPT + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/metrics.log.%i + + 1 + 10 + + + + 20MB + + + + ${metric-log-pattern} + + + + + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/supportability.log + + + + + SUPPORTABILITY_MARKER + + DENY + ACCEPT + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/supportability.log.%i + + 1 + 10 + + + + 20MB + + + + ${supportability-log-pattern} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/openecomp-ui/yarn.lock b/openecomp-ui/yarn.lock index b936780821..30eeda9850 100644 --- a/openecomp-ui/yarn.lock +++ b/openecomp-ui/yarn.lock @@ -2,38 +2,6 @@ # yarn lockfile v1 -"@angular/common@~2.4.8": - version "2.4.10" - resolved "https://registry.yarnpkg.com/@angular/common/-/common-2.4.10.tgz#a3a682d2228fa30ec23dd0eb57c8e887fba26997" - -"@angular/core@~2.4.8": - version "2.4.10" - resolved "https://registry.yarnpkg.com/@angular/core/-/core-2.4.10.tgz#0b8320a65065965d998645b1f5cd3cf769b441ea" - -"@angular/forms@~2.4.8": - version "2.4.10" - resolved "https://registry.yarnpkg.com/@angular/forms/-/forms-2.4.10.tgz#062133aaade1f3b3c962f1593208c541b622fd06" - -"@angular/http@^2.4.8": - version "2.4.10" - resolved "https://registry.yarnpkg.com/@angular/http/-/http-2.4.10.tgz#ff6beade5b39c989ebf2393c49b34eebd43e9555" - -"@angular/platform-browser-dynamic@~2.4.8": - version "2.4.10" - resolved "https://registry.yarnpkg.com/@angular/platform-browser-dynamic/-/platform-browser-dynamic-2.4.10.tgz#8df25dec2b06adc690cc9bc26448deccaebcd8ec" - -"@angular/platform-browser@~2.4.8": - version "2.4.10" - resolved "https://registry.yarnpkg.com/@angular/platform-browser/-/platform-browser-2.4.10.tgz#cbf25608148fb4ffef96cc5005ba5d7b3e093906" - -"@angular/router@~3.2.1": - version "3.2.4" - resolved "https://registry.yarnpkg.com/@angular/router/-/router-3.2.4.tgz#dfec71ad072ec031364ba5d08bd6fe03fd5beadc" - -"@angular/upgrade@^2.4.8": - version "2.4.10" - resolved "https://registry.yarnpkg.com/@angular/upgrade/-/upgrade-2.4.10.tgz#b69a3ee324d4450eb1696ddc9bded1a6ec06ca52" - "@babel/code-frame@7.0.0-beta.44": version "7.0.0-beta.44" resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.0.0-beta.44.tgz#2a02643368de80916162be70865c97774f3adbd9" @@ -7591,19 +7559,24 @@ on-headers@~1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/on-headers/-/on-headers-1.0.1.tgz#928f5d0f470d49342651ea6794b0857c100693f7" -onap-ui-common@1.0.100: - version "1.0.100" - resolved "https://registry.yarnpkg.com/onap-ui-common/-/onap-ui-common-1.0.100.tgz#c0dae1d3d1c3fd2b866340d27a1179ed10a3a860" - integrity sha512-d+eaYgVgrj9B8/3iVDlkxO2jiE7wXFrvMogxxHsyM8E0Fa7wXGEGwohA4JD5nGydT84dU2vPzwkby7SZNgGpKA== +onap-ui-common@1.0.101: + version "1.0.101" + resolved "https://registry.yarnpkg.com/onap-ui-common/-/onap-ui-common-1.0.101.tgz#c79b8fb903b7d2d3f959e3b5c27b561b563d961b" + integrity sha512-wedlorlDeGCyr/L7TzZr6UgOqpQTe5RMwh5z2lpNMHapsRx9b5gHS7QSbjNST+5zb7enGpRzjH/bYV1wn4nIPw== -onap-ui-react@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/onap-ui-react/-/onap-ui-react-0.1.1.tgz#3640bdb9fb10f85104ad9dd57a9f320b0703abf3" - integrity sha512-hax7WzSMIPll9fHvKVjFbn2dIOh39fWuiy0VQKONq/ccU3f/y08Y6EzJo7rzWcwjt8bp2KDhqNZky0HwIquc6w== +onap-ui-common@^1.0.101: + version "1.0.106" + resolved "https://registry.yarnpkg.com/onap-ui-common/-/onap-ui-common-1.0.106.tgz#d7bf8e3eb1c422afcb87fc8f3eaaf5a996aa2947" + integrity sha512-Wp8BM9EObjz5EmRC4xU2+XjEoQd9IoqDZnKzB454W1qv9F5EFyjuPT1dnSyQBSmjE679QgkOCNzwrd0UbPs9cg== + +onap-ui-react@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/onap-ui-react/-/onap-ui-react-1.0.2.tgz#e99dc5a924f84a991c71a3e9c05a44a915830168" + integrity sha512-fsYpTzw+TRSmwNXZNv+oiz9ON4k56RAhoVoKuEEaO5vY6sKJgm/3PB2p3FuQZhtnZ2u4s7/eT+7Pr7EzhPeq3w== dependencies: "@storybook/react" "^3.1.5" http-loader "0.0.1" - onap-ui-common "1.0.100" + onap-ui-common "1.0.101" prop-types "^15.6.0" react "15.6.2" react-dom "15.6.2" @@ -9437,12 +9410,6 @@ rx@4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/rx/-/rx-4.1.0.tgz#a5f13ff79ef3b740fe30aa803fb09f98805d4782" -rxjs@5.4.2: - version "5.4.2" - resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-5.4.2.tgz#2a3236fcbf03df57bae06fd6972fd99e5c08fcf7" - dependencies: - symbol-observable "^1.0.1" - rxjs@^5.5.2: version "5.5.11" resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-5.5.11.tgz#f733027ca43e3bec6b994473be4ab98ad43ced87" @@ -9535,28 +9502,6 @@ scss-tokenizer@^0.2.3: js-base64 "^2.1.8" source-map "^0.4.2" -sdc-ui@1.6.62: - version "1.6.62" - resolved "https://registry.yarnpkg.com/sdc-ui/-/sdc-ui-1.6.62.tgz#738b14d3e2d2280f9be69b1fdb91b7c815e60dca" - dependencies: - "@angular/common" "~2.4.8" - "@angular/core" "~2.4.8" - "@angular/forms" "~2.4.8" - "@angular/http" "^2.4.8" - "@angular/platform-browser" "~2.4.8" - "@angular/platform-browser-dynamic" "~2.4.8" - "@angular/router" "~3.2.1" - "@angular/upgrade" "^2.4.8" - "@storybook/react" "^3.1.5" - http-loader "0.0.1" - prop-types "^15.6.0" - react "15.6.2" - react-dom "15.6.2" - reflect-metadata "^0.1.3" - rxjs "5.4.2" - svg-react-loader "^0.4.4" - zone.js "^0.8.18" - select-hose@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/select-hose/-/select-hose-2.0.0.tgz#625d8658f865af43ec962bfc376a37359a4994ca" @@ -10261,7 +10206,7 @@ symbol-observable@1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/symbol-observable/-/symbol-observable-1.0.1.tgz#8340fc4702c3122df5d22288f88283f513d3fdd4" -symbol-observable@^1.0.1, symbol-observable@^1.0.3, symbol-observable@^1.1.0: +symbol-observable@^1.0.3, symbol-observable@^1.1.0: version "1.2.0" resolved "https://registry.yarnpkg.com/symbol-observable/-/symbol-observable-1.2.0.tgz#c22688aed4eab3cdc2dfeacbb561660560a00804" @@ -11391,7 +11336,3 @@ yeoman-generator@^2.0.5: text-table "^0.2.0" through2 "^2.0.0" yeoman-environment "^2.0.5" - -zone.js@^0.8.18: - version "0.8.26" - resolved "https://registry.yarnpkg.com/zone.js/-/zone.js-0.8.26.tgz#7bdd72f7668c5a7ad6b118148b4ea39c59d08d2d" diff --git a/pom.xml b/pom.xml index 89c2c09725..802148dd0d 100644 --- a/pom.xml +++ b/pom.xml @@ -45,7 +45,6 @@ Modifications copyright (c) 2018-2019 Nokia 0.11 3.3.2 - 3.3.2 18.0 0.3.1 4.3.18.RELEASE @@ -57,14 +56,15 @@ Modifications copyright (c) 2018-2019 Nokia 2.18.0 2.4.0 3.5.0.1 + 2.1.8 1.18.2 1.9.3 2.3 4.1.0 - 1.6.1 + 1.6.1 4.1 - 2.0.1 + 2.0.1 2.4.0 @@ -152,9 +152,13 @@ Modifications copyright (c) 2018-2019 Nokia yyyyMMdd'T'HHmmss'Z' ${project.version}-${maven.build.timestamp} + + 2.4.1.Final 2.9.9 + + 1.6.0 0.8.1 @@ -537,8 +541,7 @@ Modifications copyright (c) 2018-2019 Nokia onboarding - common-app-logging - security-utils + common-app-logging common-app-api common-be catalog-dao @@ -561,8 +564,7 @@ Modifications copyright (c) 2018-2019 Nokia false - security-utils - common-app-logging + common-app-logging common-app-api common-be catalog-dao diff --git a/security-utils/.gitignore b/security-utils/.gitignore deleted file mode 100644 index ae3c172604..0000000000 --- a/security-utils/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/bin/ diff --git a/security-utils/logback-test.xml b/security-utils/logback-test.xml deleted file mode 100644 index 4b7eb955c7..0000000000 --- a/security-utils/logback-test.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n - - - - - - - diff --git a/security-utils/pom.xml b/security-utils/pom.xml deleted file mode 100644 index 19fea32c1f..0000000000 --- a/security-utils/pom.xml +++ /dev/null @@ -1,96 +0,0 @@ - - - 4.0.0 - - security-utils - - - org.openecomp.sdc - sdc-main - 1.6.0-SNAPSHOT - - - - - - junit - junit - ${junit.version} - test - - - - - org.slf4j - slf4j-api - ${slf4j-api.version} - compile - - - - org.functionaljava - functionaljava - ${functionaljava.version} - compile - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - - - create.jar.with.dependencies - package - - single - - - - - org.openecomp.sdc.security.Passwords - - - - jar-with-dependencies - - - - - - - com.github.sylvainlaurent.maven - yaml-json-validator-maven-plugin - - - validate - validate - - validate - - - - - - src/main/resources/**/*.y*ml - src/test/resources/**/*.y*ml - - - - - src/main/resources/**/*.json - src/test/resources/**/*.json - - - - - - - - - - - diff --git a/security-utils/src/main/java/org/openecomp/sdc/security/Passwords.java b/security-utils/src/main/java/org/openecomp/sdc/security/Passwords.java deleted file mode 100644 index 48c8523354..0000000000 --- a/security-utils/src/main/java/org/openecomp/sdc/security/Passwords.java +++ /dev/null @@ -1,190 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.security; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.Arrays; -import java.util.Random; - - -public class Passwords { - - private static Logger log = LoggerFactory.getLogger( Passwords.class); - private static final Random RANDOM = new SecureRandom(); - private static final int SALT = 0; - private static final int HASH = 1; - private static final String HASH_ALGORITHM = "SHA-256"; - - /** - * static utility class - */ - private Passwords() { - } - - /** - * the method calculates a hash with a generated salt for the given password - * - * @param password - * @return a "salt:hash" value - */ - public static String hashPassword(String password) { - if (password!=null){ - byte[] salt = getNextSalt(); - byte[] byteData = hash(salt, password.getBytes()); - if (byteData != null) { - return toHex(salt) + ":" + toHex(byteData); - } - } - return null; - } - - /** - * the method checks if the given password matches the calculated hash - * - * @param password - * @param expectedHash - * @return - */ - public static boolean isExpectedPassword(String password, String expectedHash) { - if (password==null && expectedHash==null) - return true; - if (password==null || expectedHash==null) //iff exactly 1 is null - return false; - if (!expectedHash.contains(":")){ - log.error("invalid password expecting hash at the prefix of the password (ex. e0277df331f4ff8f74752ac4a8fbe03b:6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0)\n" + - "\t\t\t"); - return false; - } - String[] params = expectedHash.split(":"); - return isExpectedPassword(password, params[SALT], params[HASH]); - } - - /** - * the method checks if the given password matches the calculated hash - * - * @param password - * @param salt - * @param hash - * the hash generated using the salt - * @return true if the password matched the hash - */ - public static boolean isExpectedPassword(String password, String salt, String hash) { - if ( password == null && hash == null ) - return true; - if ( salt == null ){ - log.error("salt must be initialized"); - return false; - } - //unintialized params - if ( password == null || hash == null ) - return false; - byte[] saltBytes = fromHex(salt); - byte[] hashBytes = fromHex(hash); - - byte[] byteData = hash(saltBytes, password.getBytes()); - if (byteData != null) { - return Arrays.equals(byteData, hashBytes); - } - return false; - } - - public static void main(String[] args) { - if (args.length > 1 || args.length > 0) { - System.out.println("[" + hashPassword(args[0]) + "]"); - } else { - System.out.println("no passward passed."); - } - - } - - /** - * Returns a random salt to be used to hash a password. - * - * @return a 16 bytes random salt - */ - private static byte[] getNextSalt() { - byte[] salt = new byte[16]; - RANDOM.nextBytes(salt); - return salt; - } - - /** - * hase's the salt and value using the chosen algorithm - * - * @param salt - * @param password - * @return an array of bytes resulting from the hash - */ - private static byte[] hash(byte[] salt, byte[] password) { - MessageDigest md; - byte[] byteData = null; - try { - md = MessageDigest.getInstance(HASH_ALGORITHM); - md.update(salt); - md.update(password); - byteData = md.digest(); - } catch (NoSuchAlgorithmException e) { - log.error("invalid algorithm name {}", e); - System.out.println("invalid algorithm name"); - } - return byteData; - } - - /** - * Converts a string of hexadecimal characters into a byte array. - * - * @param hex - * the hex string - * @return the hex string decoded into a byte array - */ - private static byte[] fromHex(String hex) { - if ( hex == null ) - return null; - byte[] binary = new byte[hex.length() / 2]; - for (int i = 0; i < binary.length; i++) { - binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); - } - return binary; - } - - /** - * Converts a byte array into a hexadecimal string. - * - * @param array - * the byte array to convert - * @return a length*2 character string encoding the byte array - */ - private static String toHex(byte[] array) { - BigInteger bi = new BigInteger(1, array); - String hex = bi.toString(16); - int paddingLength = (array.length * 2) - hex.length(); - if (paddingLength > 0) - return String.format("%0" + paddingLength + "d", 0) + hex; - else - return hex; - } -} diff --git a/security-utils/src/main/java/org/openecomp/sdc/security/SecurityUtil.java b/security-utils/src/main/java/org/openecomp/sdc/security/SecurityUtil.java deleted file mode 100644 index bc20e0e991..0000000000 --- a/security-utils/src/main/java/org/openecomp/sdc/security/SecurityUtil.java +++ /dev/null @@ -1,217 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.security; - -import fj.data.Either; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.spec.SecretKeySpec; -import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.NoSuchAlgorithmException; -import java.util.Base64; -import java.util.Formatter; - -public class SecurityUtil { - - private static final Logger LOG = LoggerFactory.getLogger( SecurityUtil.class ); - private static final byte[] KEY = new byte[]{-64,5,-32 ,-117 ,-44,8,-39, 1, -9, 36,-46,-81, 62,-15,-63,-75}; - public static final SecurityUtil INSTANCE = new SecurityUtil(); - public static final String ALGORITHM = "AES" ; - public static final String CHARSET = StandardCharsets.UTF_8.name(); - - private static Key secKey = null ; - - private SecurityUtil(){ super(); } - - /** - * - * cmd commands >$PROGRAM_NAME decrypt "$ENCRYPTED_MSG" - * >$PROGRAM_NAME encrypt "message" - **/ - public static void main(String[] args) throws Exception { - if ( args!=null && args.length>1){ - fj.data.Either res = null; - final String op = args[0].trim().toLowerCase(); - try{ - switch(op) { - case "decrypt": - res = INSTANCE.decrypt(Base64.getDecoder().decode(args[1]), true); - break; - case "encrypt": - res = INSTANCE.encrypt(args[1]); - break; - default: - LOG.warn("Unfamiliar command please use: \n>aes 'message to encrypt/decrypt' "); - } - }catch(Exception e){ - LOG.warn("Exception while message encryption or decryption"); - throw e; - } - LOG.debug( "output: {}", res!=null && res.isLeft() ? res.left().value() : "ERROR" ); - } - } - - - static { - Formatter formatter = new Formatter(); - try{ - secKey = generateKey( KEY, ALGORITHM ); - } - catch(Exception e){ - if(LOG.isWarnEnabled()) - { - LOG.warn(formatter.format("cannot generate key for %s", ALGORITHM).toString(), e); - } - }finally { - formatter.close(); - } - } - - - - public static Key generateKey(final byte[] key, String algorithm){ - return new SecretKeySpec(key, algorithm); - } - - //obfuscates key prefix -> ********** - public String obfuscateKey(String sensitiveData){ - - if (sensitiveData != null){ - int len = sensitiveData.length(); - StringBuilder builder = new StringBuilder(sensitiveData); - for (int i=0; i encrypt(String strDataToEncrypt){ - - if (strDataToEncrypt != null ){ - Formatter formatter = new Formatter(); - try{ - LOG.debug("Encrypt key -> {}", secKey); - Cipher aesCipherForEncryption = Cipher.getInstance("AES"); // Must specify the mode explicitly as most JCE providers default to ECB mode!! - aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, secKey); - byte[] byteDataToEncrypt = strDataToEncrypt.getBytes(); - byte[] byteCipherText = aesCipherForEncryption.doFinal(byteDataToEncrypt); - String strCipherText = new String( java.util.Base64.getMimeEncoder().encode(byteCipherText), CHARSET ); - LOG.debug("Cipher Text generated using AES is {}", strCipherText); - return Either.left(strCipherText); - } catch( NoSuchAlgorithmException | UnsupportedEncodingException e){ - if(LOG.isWarnEnabled()) - { - LOG.warn(formatter.format("cannot encrypt data unknown algorithm or missing encoding for %s",secKey.getAlgorithm()).toString(), e); - } - } catch( InvalidKeyException e){ - if(LOG.isWarnEnabled()) - { - LOG.warn(formatter.format("invalid key recieved - > %s", java.util.Base64.getDecoder().decode(secKey.getEncoded())).toString(), e); - } - } catch( IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException e){ - if(LOG.isWarnEnabled()) - { - LOG.warn("bad algorithm definition (Illegal Block Size or padding), please review you algorithm block&padding", e); - } - } - finally { - formatter.close(); - } - } - return Either.right("Cannot encrypt "+strDataToEncrypt); - } - - /** - * Decrypt the Data - * @param byteCipherText - should be valid bae64 input in the length of 16bytes - * @param isBase64Decoded - is data already base64 encoded&aligned to 16 bytes - * a. Initialize a new instance of Cipher for Decryption (normally don't reuse the same object) - * b. Decrypt the cipher bytes using doFinal method - */ - public Either decrypt(byte[] byteCipherText , boolean isBase64Decoded){ - if (byteCipherText != null){ - byte[] alignedCipherText = byteCipherText; - Formatter formatter = new Formatter(); - try{ - if (isBase64Decoded) - alignedCipherText = Base64.getDecoder().decode(byteCipherText); - LOG.debug("Decrypt key -> {}", secKey.getEncoded()); - Cipher aesCipherForDecryption = Cipher.getInstance("AES"); // Must specify the mode explicitly as most JCE providers default to ECB mode!! - aesCipherForDecryption.init(Cipher.DECRYPT_MODE, secKey); - byte[] byteDecryptedText = aesCipherForDecryption.doFinal(alignedCipherText); - String strDecryptedText = new String(byteDecryptedText); - String obfuscateKey = obfuscateKey( strDecryptedText ); - LOG.debug("Decrypted Text message is: {}" , obfuscateKey); - return Either.left(strDecryptedText); - } catch( NoSuchAlgorithmException e){ - if(LOG.isWarnEnabled()) - { - LOG.warn(formatter.format("cannot encrypt data unknown algorithm or missing encoding for %s", secKey.getAlgorithm()).toString(), e); - } - } catch( InvalidKeyException e){ - if(LOG.isWarnEnabled()) - { - LOG.warn(formatter.format("invalid key recieved - > %s", java.util.Base64.getDecoder().decode(secKey.getEncoded())).toString(), e); - } - } catch( IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException e){ - if(LOG.isWarnEnabled()) - { - LOG.warn( "bad algorithm definition (Illegal Block Size or padding), please review you algorithm block&padding", e); - } - }finally { - formatter.close(); - } - } - return Either.right("Decrypt FAILED"); - } - - public Either decrypt(String byteCipherText){ - Formatter formatter = new Formatter(); - try { - return decrypt(byteCipherText.getBytes(CHARSET),true); - } catch( UnsupportedEncodingException e ){ - if(LOG.isWarnEnabled()) - { - LOG.warn(formatter.format("Missing encoding for %s",secKey.getAlgorithm()).toString(), e); - } - }finally { - formatter.close(); - } - return Either.right("Decrypt FAILED"); - } -} diff --git a/security-utils/src/test/java/org/openecomp/sdc/security/PasswordsTest.java b/security-utils/src/test/java/org/openecomp/sdc/security/PasswordsTest.java deleted file mode 100644 index 9310917ba1..0000000000 --- a/security-utils/src/test/java/org/openecomp/sdc/security/PasswordsTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.security; - -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class PasswordsTest { - - @Test - public void hashPassword() throws Exception { - String hash = Passwords.hashPassword("hello1234"); - assertTrue(Passwords.isExpectedPassword("hello1234", hash)); - - //test different salt-> result in different hash - String hash2 = Passwords.hashPassword("hello1234"); - assertFalse(hash.equals(hash2)); - - String hash3 = Passwords.hashPassword(""); - assertTrue(Passwords.isExpectedPassword("", hash3)); - - String hash4 = Passwords.hashPassword(null); - assertTrue(hash4 == null); - } - - @Test - public void isExpectedPassword() throws Exception { - //region isExpectedPassword(String password, String salt, String hash) - assertTrue(Passwords.isExpectedPassword(null, null, null)); - //valid hash - assertTrue(Passwords.isExpectedPassword("hello1234", "e0277df331f4ff8f74752ac4a8fbe03b", "6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0")); - //invalid salt - assertFalse(Passwords.isExpectedPassword("hello1234", "c0000df331f4ff8f74752ac4a00be03c", "6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0")); - assertFalse(Passwords.isExpectedPassword("hello1234", null, "6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0")); - //exacly 1 param uninitialized - assertFalse(Passwords.isExpectedPassword("hello1234", "", null)); - assertFalse(Passwords.isExpectedPassword(null, "", "hello1234")); - //no salt & no hash - assertFalse(Passwords.isExpectedPassword("hello1234", null, "hello1234")); - //endregion - - //region isExpectedPassword(String password, String expectedHash) - assertTrue(Passwords.isExpectedPassword(null, null)); - //valid hash - assertTrue(Passwords.isExpectedPassword("hello1234", "e0277df331f4ff8f74752ac4a8fbe03b:6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0")); - //invalid salt - assertFalse(Passwords.isExpectedPassword("hello1234", "c0000df331f4ff8f74752ac4a00be03c:6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0")); - //exacly 1 param uninitialized - assertFalse(Passwords.isExpectedPassword("hello1234", null)); - assertFalse(Passwords.isExpectedPassword(null, "hello1234")); - //no salt & no hash - assertFalse(Passwords.isExpectedPassword("hello1234", "hello1234")); - //endregion - } - - @Test - public void hashtest() { - String password = "123456"; - String hash = Passwords.hashPassword(password); - assertTrue(Passwords.isExpectedPassword(password, hash)); - password = "1sdfgsgd23456"; - hash = Passwords.hashPassword(password); - assertTrue(Passwords.isExpectedPassword(password, hash)); - password = "1sdfgsgd2345((*&%$%6"; - hash = Passwords.hashPassword(password); - assertTrue(Passwords.isExpectedPassword(password, hash)); - password = ""; - hash = Passwords.hashPassword(password); - assertTrue(Passwords.isExpectedPassword(password, hash)); - password = " "; - hash = Passwords.hashPassword(password); - assertTrue(Passwords.isExpectedPassword(password, hash)); - } - - -} diff --git a/security-utils/src/test/java/org/openecomp/sdc/security/SecurityUtilTest.java b/security-utils/src/test/java/org/openecomp/sdc/security/SecurityUtilTest.java deleted file mode 100644 index e114a468e4..0000000000 --- a/security-utils/src/test/java/org/openecomp/sdc/security/SecurityUtilTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.security; - -import org.junit.Test; - -import java.util.Base64; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - -public class SecurityUtilTest { - - @Test - public void encryptDecryptAES128() throws Exception { - String data = "decrypt SUCCESS!!"; - String encrypted = SecurityUtil.INSTANCE.encrypt(data).left().value(); - assertNotEquals( data, encrypted ); - byte[] decryptMsg = Base64.getDecoder().decode(encrypted); - assertEquals( SecurityUtil.INSTANCE.decrypt( decryptMsg , false ).left().value() ,data ); - assertEquals( SecurityUtil.INSTANCE.decrypt( encrypted.getBytes() , true ).left().value() ,data ); - } - - @Test - public void obfuscateKey() throws Exception { - String key = "abcdefghij123456"; - String expectedkey = "********ij123456"; - String obfuscated = SecurityUtil.INSTANCE.obfuscateKey( key ); - System.out.println( obfuscated ); - assertEquals( obfuscated , expectedkey ); - } -} diff --git a/test-apis-ci/pom.xml b/test-apis-ci/pom.xml index 807b59d63b..68e0df0a9d 100644 --- a/test-apis-ci/pom.xml +++ b/test-apis-ci/pom.xml @@ -88,14 +88,12 @@ org.openecomp.sdc common-app-api ${project.version} - compile org.openecomp.sdc.be common-be ${project.version} - compile @@ -103,7 +101,6 @@ org.openecomp.sdc.be catalog-model ${project.version} - compile @@ -111,7 +108,6 @@ org.openecomp.sdc.be catalog-dao ${project.version} - compile diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java index 76c17f0375..85e7cf6b29 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java @@ -25,6 +25,7 @@ import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceInstantiationType; import java.util.ArrayList; +import java.util.Collections; public class ServiceReqDetails extends ComponentReqDetails { @@ -32,7 +33,8 @@ public class ServiceReqDetails extends ComponentReqDetails { protected String serviceRole = "MyServiceRole"; protected String namingPolicy = "MyServiceNamingPolicy"; protected Boolean ecompGeneratedNaming = true; - protected String instantiationType = ServiceInstantiationType.A_LA_CARTE.getValue(); + protected String instantiationType = ServiceInstantiationType.A_LA_CARTE.getValue(); + protected String serviceFunction = ""; public String getServiceType() { return serviceType; @@ -70,6 +72,14 @@ public class ServiceReqDetails extends ComponentReqDetails { this.ecompGeneratedNaming = ecompGeneratedNaming; } + public String getServiceFunction() { + return serviceFunction; + } + + public void setServiceFunction(String serviceFunction) { + this.serviceFunction = serviceFunction; + } + public ServiceReqDetails(String serviceName, String category, ArrayList tags, String description, String contactId, String icon, String instantiationType) { this.name = serviceName; @@ -78,8 +88,10 @@ public class ServiceReqDetails extends ComponentReqDetails { this.contactId = contactId; this.icon = icon; projectCode = "12345"; + serviceFunction = "serviceFunction name"; CategoryDefinition categoryDefinition = new CategoryDefinition(); categoryDefinition.setName(category); + categoryDefinition.setIcons(Collections.singletonList(icon)); categories = new ArrayList<>(); categories.add(categoryDefinition); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/UpdateResourceMetadataTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/UpdateResourceMetadataTest.java index bfd64c34f7..7b959d8ddf 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/UpdateResourceMetadataTest.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/UpdateResourceMetadataTest.java @@ -153,7 +153,7 @@ public class UpdateResourceMetadataTest extends ComponentBaseTest { updatedResourceDetails.setLastUpdaterFullName("Viktor Tzoy"); updatedResourceDetails.setCreationDate(new Long(4444)); updatedResourceDetails.setLastUpdateDate(new Long("534535")); - updatedResourceDetails.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); + updatedResourceDetails.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); updatedResourceDetails.setCost("6.1"); updatedResourceDetails.setLicenseType("Installation"); updatedResourceDetails.setUUID("dfsfsdf"); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ChangeServiceDistributionStatusApiTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ChangeServiceDistributionStatusApiTest.java deleted file mode 100644 index 5bb01d5dd6..0000000000 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ChangeServiceDistributionStatusApiTest.java +++ /dev/null @@ -1,1002 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.ci.tests.execute.service; - -import org.junit.Rule; -import org.junit.rules.TestName; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; -import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; -import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; -import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; -import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; -import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; -import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; -import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; -import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject; -import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; -import org.openecomp.sdc.ci.tests.utils.DbUtils; -import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils; -import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; -import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; -import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils; -import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; -import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; -import org.openecomp.sdc.ci.tests.utils.validation.ServiceValidationUtils; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static org.testng.AssertJUnit.*; - -public class ChangeServiceDistributionStatusApiTest extends ComponentBaseTest { - - protected ResourceReqDetails resourceDetails; - protected ServiceReqDetails serviceDetails; - protected User sdncDesignerDetails; - protected User sdncAdminDetails; - protected User sdncGovernorDeatails; - protected User sdncTesterDetails; - protected User sdncOpsDetails; - protected ComponentInstanceReqDetails resourceInstanceReqDetails; - protected Component resourceDetailsVFCcomp; - protected Component serviceDetailsCompp; - - private String userRemarks = "commentTest"; - - private List variablesAsList; - - @Rule - public static TestName name = new TestName(); - - public ChangeServiceDistributionStatusApiTest() throws Exception { - super(name, ChangeServiceDistributionStatusApiTest.class.getName()); - - } - - @BeforeMethod - public void init() throws Exception { - - variablesAsList = new ArrayList(); - sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); - sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); - sdncGovernorDeatails = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR); - sdncTesterDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); - sdncOpsDetails = ElementFactory.getDefaultUser(UserRoleEnum.OPS); - resourceDetailsVFCcomp = AtomicOperationUtils - .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value(); - AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVFCcomp, UserRoleEnum.DESIGNER, - true, true); - - AtomicOperationUtils.changeComponentState(resourceDetailsVFCcomp, UserRoleEnum.DESIGNER, - LifeCycleStatesEnum.CERTIFY, true); - Service serviceServ = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value(); - AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVFCcomp, serviceServ, - UserRoleEnum.DESIGNER, true); - - serviceDetails = new ServiceReqDetails(serviceServ); - - } - - // -----------------------------------------------T E S T - // S--------------------------------------------// - - @Test - public void approveNotCertifiedService_checkout() throws Exception { - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 403, serviceDetails.getVersion()); - - variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(), - variablesAsList, changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - validateAudit("DApprove", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, - DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails); - } - - @Test - public void approveNotCertifiedService_checkedin() throws Exception { - RestResponse checkinResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, - serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); - assertEquals(200, checkinResp.getErrorCode().intValue()); - - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 403, serviceDetails.getVersion()); - - variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(), - variablesAsList, changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - validateAudit("DApprove", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, - DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails); - } - - @Test - public void approveNotCertifiedService_inProgress() throws Exception { - RestResponse certReqResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, - serviceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST); - assertEquals(200, certReqResp.getErrorCode().intValue()); - - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 403, serviceDetails.getVersion()); - - variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(), - variablesAsList, changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - // ErrorInfo errorInfo = - // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name()); - // String auditAction="DApprove"; - // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = - // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails, - // version, sdncAdminDetails); - // expectedResourceAuditJavaObject.setAction(auditAction); - // expectedResourceAuditJavaObject.setResourceType("Service"); - // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.READY_FOR_CERTIFICATION.name()); - // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setComment(userRemarks); - // expectedResourceAuditJavaObject.setStatus("403"); - // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId() - // + ": " + errorInfo.getMessage(), version, - // serviceDetails.getServiceName())); - // - // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, - // auditAction); - - validateAudit("DApprove", LifecycleStateEnum.READY_FOR_CERTIFICATION, - DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails); - - } - - @Test - public void approveNotCertifiedService_readyForCer() throws Exception { - approveNotCertifiedService_inProgress(); - DbUtils.deleteFromEsDbByPattern("_all"); - - RestResponse startCertResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, - serviceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION); - assertEquals(200, startCertResp.getErrorCode().intValue()); - - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 403, serviceDetails.getVersion()); - - variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(), - variablesAsList, changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - // ErrorInfo errorInfo = - // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name()); - // String auditAction="DApprove"; - // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = - // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails, - // version, sdncAdminDetails); - // expectedResourceAuditJavaObject.setAction(auditAction); - // expectedResourceAuditJavaObject.setResourceType("Service"); - // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); - // expectedResourceAuditJavaObject.setPrevState(""); - // expectedResourceAuditJavaObject.setDprevStatus(""); - // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setComment(userRemarks); - // expectedResourceAuditJavaObject.setStatus("403"); - // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId() - // + ": " + errorInfo.getMessage(), version, - // serviceDetails.getServiceName())); - // expectedResourceAuditJavaObject.setPrevVersion("0.1"); - // - // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, - // auditAction); - - validateAudit("DApprove", LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, - DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails); - } - - @Test - public void rejectNotCertifiedService_checkeout() throws Exception { - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 403, serviceDetails.getVersion()); - - variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(), - variablesAsList, changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - // ErrorInfo errorInfo = - // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name()); - // String auditAction="DReject"; - // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = - // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails, - // version, sdncAdminDetails); - // expectedResourceAuditJavaObject.setAction(auditAction); - // expectedResourceAuditJavaObject.setResourceType("Service"); - // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - // expectedResourceAuditJavaObject.setPrevState(""); - // expectedResourceAuditJavaObject.setDprevStatus(""); - // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setComment(userRemarks); - // expectedResourceAuditJavaObject.setStatus("403"); - // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId() - // + ": " + errorInfo.getMessage(), version, - // serviceDetails.getServiceName())); - // expectedResourceAuditJavaObject.setPrevVersion("0.1"); - // - // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, - // auditAction); - - validateAudit("DReject", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, - DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails); - } - - @Test - public void rejectNotCertifiedService_checkedin() throws Exception { - RestResponse startCertResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, - serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); - assertEquals(200, startCertResp.getErrorCode().intValue()); - - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 403, serviceDetails.getVersion()); - - variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(), - variablesAsList, changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - // ErrorInfo errorInfo = - // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name()); - // String auditAction="DReject"; - // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = - // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails, - // version, sdncAdminDetails); - // expectedResourceAuditJavaObject.setAction(auditAction); - // expectedResourceAuditJavaObject.setResourceType("Service"); - // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.name()); - // expectedResourceAuditJavaObject.setPrevState(""); - // expectedResourceAuditJavaObject.setDprevStatus(""); - // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setComment(userRemarks); - // expectedResourceAuditJavaObject.setStatus("403"); - // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId() - // + ": " + errorInfo.getMessage(), version, - // serviceDetails.getServiceName())); - // expectedResourceAuditJavaObject.setPrevVersion("0.1"); - // - // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, - // auditAction); - - validateAudit("DReject", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, - DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails); - } - - @Test - public void rejectNotCertifiedService_inProgress() throws Exception { - RestResponse startCertResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, - serviceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST); - assertEquals(200, startCertResp.getErrorCode().intValue()); - - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 403, serviceDetails.getVersion()); - - variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(), - variablesAsList, changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - // ErrorInfo errorInfo = - // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name()); - // String auditAction="DReject"; - // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = - // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails, - // version, sdncAdminDetails); - // expectedResourceAuditJavaObject.setAction(auditAction); - // expectedResourceAuditJavaObject.setResourceType("Service"); - // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.READY_FOR_CERTIFICATION.name()); - // expectedResourceAuditJavaObject.setPrevState(""); - // expectedResourceAuditJavaObject.setDprevStatus(""); - // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setComment(userRemarks); - // expectedResourceAuditJavaObject.setStatus("403"); - // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId() - // + ": " + errorInfo.getMessage(), version, - // serviceDetails.getServiceName())); - // expectedResourceAuditJavaObject.setPrevVersion("0.1"); - // - // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, - // auditAction); - - validateAudit("DReject", LifecycleStateEnum.READY_FOR_CERTIFICATION, - DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails); - } - - @Test - public void rejectNotCertifiedService_readyForCer() throws Exception { - rejectNotCertifiedService_inProgress(); - DbUtils.deleteFromEsDbByPattern("_all"); - - RestResponse startCertResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, - serviceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION); - assertEquals(200, startCertResp.getErrorCode().intValue()); - - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 403, serviceDetails.getVersion()); - - variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(), - variablesAsList, changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - // ErrorInfo errorInfo = - // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name()); - // String auditAction="DReject"; - // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = - // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails, - // version, sdncAdminDetails); - // expectedResourceAuditJavaObject.setAction(auditAction); - // expectedResourceAuditJavaObject.setResourceType("Service"); - // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); - // expectedResourceAuditJavaObject.setPrevState(""); - // expectedResourceAuditJavaObject.setDprevStatus(""); - // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setComment(userRemarks); - // expectedResourceAuditJavaObject.setStatus("403"); - // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId() - // + ": " + errorInfo.getMessage(), version, - // serviceDetails.getServiceName())); - // expectedResourceAuditJavaObject.setPrevVersion("0.1"); - // - // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, - // auditAction); - - validateAudit("DReject", LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, - DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails); - - } - - @Test - public void approveCertifiedService_bysdncGovernorDeatails() throws Exception { - - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncGovernorDeatails, 200, certifyService.getVersion()); - getDistrubtionStatusValue(changeDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_APPROVED); - - RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_APPROVED); - - validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - DistributionStatusEnum.DISTRIBUTION_APPROVED, null, null, sdncGovernorDeatails); - } - - @Test - public void approveCertifiedService_bysdncAdminDetails() throws Exception { - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 200, certifyService.getVersion()); - getDistrubtionStatusValue(changeDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_APPROVED); - - RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_APPROVED); - - validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - DistributionStatusEnum.DISTRIBUTION_APPROVED, null, null, sdncAdminDetails); - } - - @Test - public void approveCertifiedService_byDesigner() throws Exception { - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncDesignerDetails, 409, certifyService.getVersion()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), - changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - // ErrorInfo errorInfo = - // utils.parseYaml(ActionStatus.RESTRICTED_OPERATION.name()); - // String auditAction="DApprove"; - // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = - // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService, - // certifyService.getVersion(), sdncDesignerDetails); - // expectedResourceAuditJavaObject.setAction(auditAction); - // expectedResourceAuditJavaObject.setResourceType("Service"); - // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name()); - // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setStatus("409"); - // expectedResourceAuditJavaObject.setDesc(errorInfo.getMessageId() + ": - // " + errorInfo.getMessage()); - // expectedResourceAuditJavaObject.setComment(userRemarks); - // - // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, - // auditAction); - - validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION, - sdncDesignerDetails); - } - - @Test - public void approveCertifiedService_byTester() throws Exception { - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncTesterDetails, 409, certifyService.getVersion()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), - changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - // ErrorInfo errorInfo = - // utils.parseYaml(ActionStatus.RESTRICTED_OPERATION.name()); - // String auditAction="DApprove"; - // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = - // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService, - // certifyService.getVersion(), sdncTesterDetails); - // expectedResourceAuditJavaObject.setAction(auditAction); - // expectedResourceAuditJavaObject.setResourceType("Service"); - // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name()); - // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setStatus("409"); - // expectedResourceAuditJavaObject.setDesc(errorInfo.getMessageId() + ": - // " + errorInfo.getMessage()); - // expectedResourceAuditJavaObject.setComment(userRemarks); - // - // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, - // auditAction); - - validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION, - sdncTesterDetails); - } - - @Test - public void approveCertifiedService_byOps() throws Exception { - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncOpsDetails, 409, certifyService.getVersion()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), - changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION, - sdncOpsDetails); - - } - - @Test - public void rejectCertifiedService_bysdncGovernorDeatails() throws Exception { - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncGovernorDeatails, 200, certifyService.getVersion()); - getDistrubtionStatusValue(changeDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_REJECTED); - - RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_REJECTED); - - // String auditAction="DReject"; - // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = - // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService, - // certifyService.getVersion(), sdncGovernorDeatails); - // expectedResourceAuditJavaObject.setAction(auditAction); - // expectedResourceAuditJavaObject.setResourceType("Service"); - // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name()); - // expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); - // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_REJECTED.name()); - // expectedResourceAuditJavaObject.setComment(userRemarks); - // expectedResourceAuditJavaObject.setPrevVersion("0.1"); - // - // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, - // auditAction); - - validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - DistributionStatusEnum.DISTRIBUTION_REJECTED, null, null, sdncGovernorDeatails); - - } - - @Test - public void rejectCertifiedService_bysdncAdminDetails() throws Exception { - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 200, certifyService.getVersion()); - getDistrubtionStatusValue(changeDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_REJECTED); - - RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_REJECTED); - - // String auditAction="DReject"; - // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = - // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService, - // certifyService.getVersion(), sdncAdminDetails); - // expectedResourceAuditJavaObject.setAction(auditAction); - // expectedResourceAuditJavaObject.setResourceType("Service"); - // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name()); - // expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); - // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_REJECTED.name()); - // expectedResourceAuditJavaObject.setComment(userRemarks); - // expectedResourceAuditJavaObject.setPrevVersion("0.1"); - // - // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, - // auditAction); - - validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - DistributionStatusEnum.DISTRIBUTION_REJECTED, null, null, sdncAdminDetails); - } - - @Test - public void rejectCertifiedService_byDesigner() throws Exception { - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncDesignerDetails, 409, certifyService.getVersion()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), - changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - // ErrorInfo errorInfo = - // utils.parseYaml(ActionStatus.RESTRICTED_OPERATION.name()); - // String auditAction="DReject"; - // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = - // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService, - // certifyService.getVersion(), sdncDesignerDetails); - // expectedResourceAuditJavaObject.setAction(auditAction); - // expectedResourceAuditJavaObject.setResourceType("Service"); - // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name()); - // expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); - // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setStatus("409"); - // expectedResourceAuditJavaObject.setDesc(errorInfo.getMessageId() + ": - // " + errorInfo.getMessage()); - // expectedResourceAuditJavaObject.setComment(userRemarks); - // expectedResourceAuditJavaObject.setPrevVersion("0.1"); - // - // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, - // auditAction); - - validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION, - sdncDesignerDetails); - } - - @Test - public void rejectCertifiedService_byTester() throws Exception { - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncTesterDetails, 409, certifyService.getVersion()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), - changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - // ErrorInfo errorInfo = - // utils.parseYaml(ActionStatus.RESTRICTED_OPERATION.name()); - // String auditAction="DReject"; - // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = - // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService, - // certifyService.getVersion(), sdncTesterDetails); - // expectedResourceAuditJavaObject.setAction(auditAction); - // expectedResourceAuditJavaObject.setResourceType("Service"); - // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name()); - // expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); - // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setStatus("409"); - // expectedResourceAuditJavaObject.setDesc(errorInfo.getMessageId() + ": - // " + errorInfo.getMessage()); - // expectedResourceAuditJavaObject.setComment(userRemarks); - // expectedResourceAuditJavaObject.setPrevVersion("0.1"); - // - // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, - // auditAction); - - validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION, - sdncTesterDetails); - } - - @Test - public void rejectCertifiedService_byOps() throws Exception { - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncOpsDetails, 409, certifyService.getVersion()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList(), - changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - // ErrorInfo errorInfo = - // utils.parseYaml(ActionStatus.RESTRICTED_OPERATION.name()); - // String auditAction="DReject"; - // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = - // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService, - // certifyService.getVersion(), sdncOpsDetails); - // expectedResourceAuditJavaObject.setAction(auditAction); - // expectedResourceAuditJavaObject.setResourceType("Service"); - // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name()); - // expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); - // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); - // expectedResourceAuditJavaObject.setStatus("409"); - // expectedResourceAuditJavaObject.setDesc(errorInfo.getMessageId() + ": - // " + errorInfo.getMessage()); - // expectedResourceAuditJavaObject.setComment(userRemarks); - // expectedResourceAuditJavaObject.setPrevVersion("0.1"); - // - // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, - // auditAction); - - validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, - DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION, - sdncOpsDetails); - } - - @Test - public void approveServiceNotFound() throws Exception { - String previuosId = serviceDetails.getUniqueId(); - serviceDetails.setUniqueId("dummyId"); - - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 404, serviceDetails.getVersion()); - serviceDetails.setUniqueId(previuosId); - - variablesAsList = Arrays.asList("dummyId"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variablesAsList, - changeDistStatusAndValidate.getResponse()); - - } - - @Test - public void rejectServiceNotFound() throws Exception { - String previuosId = serviceDetails.getUniqueId(); - serviceDetails.setUniqueId("dummyId"); - - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 404, serviceDetails.getVersion()); - serviceDetails.setUniqueId(previuosId); - - variablesAsList = Arrays.asList("dummyId"); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variablesAsList, - changeDistStatusAndValidate.getResponse()); - - } - - @Test - public void rejectService_emptyComment() throws Exception { - userRemarks = ""; - - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 400, certifyService.getVersion()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList(), - changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - } - - @Test - public void rejectService_nullComment() throws Exception { - userRemarks = null; - - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 400, certifyService.getVersion()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList(), - changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - } - - @Test - public void rejectService_spaceComment() throws Exception { - userRemarks = " "; - - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 400, certifyService.getVersion()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList(), - changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - } - - @Test - public void approveService_emptyComment() throws Exception { - userRemarks = ""; - - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 400, certifyService.getVersion()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList(), - changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - } - - @Test - public void approveService_nullComment() throws Exception { - userRemarks = null; - - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 400, certifyService.getVersion()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList(), - changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - } - - @Test - public void approveService_spaceComment() throws Exception { - userRemarks = " "; - - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 400, certifyService.getVersion()); - ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList(), - changeDistStatusAndValidate.getResponse()); - - RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - } - - @Test - public void distributionStatusChange_approve_Reject_AprroveBysdncAdminDetails() throws Exception { - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - - RestResponse approveDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncGovernorDeatails, 200, certifyService.getVersion()); - getDistrubtionStatusValue(approveDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_APPROVED); - - DbUtils.deleteFromEsDbByPattern("_all"); - RestResponse rejectDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncGovernorDeatails, 200, certifyService.getVersion()); - getDistrubtionStatusValue(rejectDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_REJECTED); - - validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_APPROVED, - DistributionStatusEnum.DISTRIBUTION_REJECTED, null, null, sdncGovernorDeatails); - - DbUtils.deleteFromEsDbByPattern("_all"); - RestResponse secondApproveDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 200, certifyService.getVersion()); - getDistrubtionStatusValue(secondApproveDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_APPROVED); - - validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_REJECTED, - DistributionStatusEnum.DISTRIBUTION_APPROVED, null, null, sdncAdminDetails); - - } - - @Test - public void distributeNotCertifiedServiceTest() throws Exception { - RestResponse approveDistStatusAndValidate = changeDistStatusAndValidate(DistributionStatusEnum.DISTRIBUTED, - sdncGovernorDeatails, 200, serviceDetails.getVersion()); - - RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTED); - - } - - @Test - public void distributeCertifiedServiceTest() throws Exception { - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - RestResponse approveDistStatusAndValidate = changeDistStatusAndValidate(DistributionStatusEnum.DISTRIBUTED, - sdncGovernorDeatails, 200, certifyService.getVersion()); - - RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails); - getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTED); - - } - - @Test - public void approveCheckedoutCertifiedServiceTest() throws Exception { - RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails); - Service certifyServiceServ = ResponseParser - .convertServiceResponseToJavaObject(certifyServiceResp.getResponse()); - ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ); - RestResponse approveDistStatusAndValidate = changeDistStatusAndValidate( - DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncGovernorDeatails, 200, certifyService.getVersion()); - getDistrubtionStatusValue(approveDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_APPROVED); - - RestResponse checkoutResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, - serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); - assertEquals(200, checkoutResp.getErrorCode().intValue()); - // Utils r = new Utils(); - - String distributionStatus = ResponseParser.getValueFromJsonResponse(checkoutResp.getResponse(), - "distributionStatus"); - // Utils r1 = new Utils(); - String lifecycleState = ResponseParser.getValueFromJsonResponse(checkoutResp.getResponse(), "lifecycleState"); - - assertTrue("NOT_CERTIFIED_CHECKOUT".equals(lifecycleState)); - assertTrue("DISTRIBUTION_NOT_APPROVED".equals(distributionStatus)); - } - - private RestResponse changeDistStatusAndValidate(DistributionStatusEnum distStatus, User user, int errorCode, - String serviceVersion) throws Exception { - RestResponse distributionResponse = LifecycleRestUtils.changeDistributionStatus(serviceDetails, serviceVersion, - user, userRemarks, distStatus); - assertNotNull(distributionResponse); - assertNotNull(distributionResponse.getErrorCode()); - assertEquals(errorCode, distributionResponse.getErrorCode().intValue()); - - if (userRemarks == " " || userRemarks == null) { - userRemarks = ""; - } - - return distributionResponse; - } - - private void getDistrubtionStatusValue(RestResponse response, DistributionStatusEnum expectedDistributionValue) - throws Exception { - String actualDistributionValue = ResponseParser.getValueFromJsonResponse(response.getResponse(), - "distributionStatus"); - assertEquals(expectedDistributionValue.name(), actualDistributionValue); - } - - private void validateAudit(String Action, LifecycleStateEnum currState, DistributionStatusEnum dPrevStatus, - DistributionStatusEnum dCurrStatus, String status, ActionStatus errorInfoFromFile, User user) - throws Exception { - - ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils - .constructFieldsForAuditValidation(serviceDetails, serviceDetails.getVersion(), user); - expectedResourceAuditJavaObject.setAction(Action); - expectedResourceAuditJavaObject.setResourceType("Service"); - expectedResourceAuditJavaObject.setCurrState(currState.name()); - expectedResourceAuditJavaObject.setDprevStatus(dPrevStatus.name()); - expectedResourceAuditJavaObject.setDcurrStatus(dCurrStatus.name()); - expectedResourceAuditJavaObject.setComment(userRemarks); - expectedResourceAuditJavaObject.setDesc("OK"); - - if (errorInfoFromFile != null) { - ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorInfoFromFile.name()); - expectedResourceAuditJavaObject - .setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variablesAsList)); - } - - if (status != null) - expectedResourceAuditJavaObject.setStatus(status); - - if (currState != LifecycleStateEnum.CERTIFIED) { - expectedResourceAuditJavaObject.setModifierName(""); - } - - AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, Action); - } - - // private ServiceReqDetails certifyService() throws Exception - // { - // ServiceReqDetails certifyService = - // LifecycleRestUtils.certifyService(serviceDetails, - // serviceDetails.getVersion(), sdncAdminDetails); - //// version = certifyService.getVersion(); - // - // return certifyService; - // } - -} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/user/GovernorWorkspaceApiTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/user/GovernorWorkspaceApiTest.java index 5a56af5d4c..c5a55614d9 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/user/GovernorWorkspaceApiTest.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/user/GovernorWorkspaceApiTest.java @@ -174,7 +174,7 @@ public class GovernorWorkspaceApiTest extends ComponentBaseTest { throws Exception { RestResponse res = LifecycleRestUtils.sendApproveDistribution(user, serviceDetails.getUniqueId(), userRemarks); assertEquals(200, res.getErrorCode().intValue()); - ServiceValidationUtils.validateDistrubtionStatusValue(res, DistributionStatusEnum.DISTRIBUTION_APPROVED); + ServiceValidationUtils.validateDistrubtionStatusValue(res, DistributionStatusEnum.DISTRIBUTED); } protected void rejectDistributionStatusOfService(ServiceReqDetails serviceDetails, User user) throws Exception { @@ -185,7 +185,7 @@ public class GovernorWorkspaceApiTest extends ComponentBaseTest { throws Exception { RestResponse res = LifecycleRestUtils.rejectDistribution(serviceDetails, version, user, userRemarks); assertEquals(200, res.getErrorCode().intValue()); - ServiceValidationUtils.validateDistrubtionStatusValue(res, DistributionStatusEnum.DISTRIBUTION_REJECTED); + ServiceValidationUtils.validateDistrubtionStatusValue(res, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); } protected JSONArray getFollowedListAsJsonArray(User user) throws Exception { diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java index 43c93e47a6..f0efd96079 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java @@ -64,7 +64,9 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import static org.junit.Assert.assertFalse; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; @@ -308,13 +310,13 @@ public final class AtomicOperationUtils { // *********** LIFECYCLE *************** - public static Pair changeComponentState(Component component, UserRoleEnum userRole, LifeCycleStatesEnum targetState, Boolean validateState) throws Exception { + public static Pair changeComponentState(Component component, UserRoleEnum userRole, LifeCycleStatesEnum targetState, Boolean validateState) throws Exception { - Boolean isValidationFailed = false; - RestResponse lifeCycleStatesResponse = null; - User defaultUser; + Boolean isValidationFailed = false; + RestResponse lifeCycleStatesResponse = null; + User defaultUser; - LifeCycleStatesEnum currentCompState = LifeCycleStatesEnum.findByCompState(component.getLifecycleState().toString()); + LifeCycleStatesEnum currentCompState = LifeCycleStatesEnum.findByCompState(component.getLifecycleState().toString()); if (currentCompState == targetState) { component = getComponentObject(component, userRole); @@ -325,30 +327,17 @@ public final class AtomicOperationUtils { if (currentCompState.equals(LifeCycleStatesEnum.CHECKIN) && targetState.equals(LifeCycleStatesEnum.CHECKOUT)) { lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKIN.toString()); lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKOUT.toString()); -// TODO Andrey added component type condition } else { - if (componentType.equals("Resource")) { - lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKOUT.toString()); - lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKIN.toString()); - lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CERTIFY.toString()); - } else { - lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKOUT.toString()); - lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKIN.toString()); - lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CERTIFICATIONREQUEST.toString()); - lifeCycleStatesEnumList.add(LifeCycleStatesEnum.STARTCERTIFICATION.toString()); - lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CERTIFY.toString()); - } + lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKOUT.toString()); + lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKIN.toString()); + lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CERTIFY.toString()); } for (int i = 0; i < lifeCycleStatesEnumList.size(); i++) { if (lifeCycleStatesEnumList.get(i).equals(currentCompState.name())) { int a; a = (i == lifeCycleStatesEnumList.size() - 1) ? 0 : i + 1; for (int n = a; n < lifeCycleStatesEnumList.size(); n++) { - if ((lifeCycleStatesEnumList.get(n).equals(LifeCycleStatesEnum.STARTCERTIFICATION.name()) || lifeCycleStatesEnumList.get(n).equals(LifeCycleStatesEnum.CERTIFY.name())) && !componentType.equals("Resource")) { - defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); - } else { - defaultUser = ElementFactory.getDefaultUser(userRole); - } + defaultUser = ElementFactory.getDefaultUser(userRole); lifeCycleStatesResponse = LifecycleRestUtils.changeComponentState(component, defaultUser, LifeCycleStatesEnum.findByState(lifeCycleStatesEnumList.get(n))); if (lifeCycleStatesResponse.getErrorCode() != LifecycleRestUtils.STATUS_CODE_SUCCESS) isValidationFailed = true; @@ -362,7 +351,6 @@ public final class AtomicOperationUtils { if (validateState && isValidationFailed) { assertTrue("change state to [" + targetState.getState() + "] failed" + lifeCycleStatesResponse.getResponse(), false); - return Pair.of(componentJavaObject, lifeCycleStatesResponse); } @@ -383,7 +371,7 @@ public final class AtomicOperationUtils { ServiceReqDetails serviceDetails = new ServiceReqDetails(service); RestResponse distributionService = null; - RestResponse approveDistribution = LifecycleRestUtils.changeDistributionStatus(serviceDetails, null, governotUser, "approveService", DistributionStatusEnum.DISTRIBUTION_APPROVED); + RestResponse approveDistribution = LifecycleRestUtils.changeDistributionStatus(serviceDetails, null, governotUser, "approveService", DistributionStatusEnum.DISTRIBUTED); if (approveDistribution.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) { distributionService = LifecycleRestUtils.changeDistributionStatus(serviceDetails, null, opsUser, "approveService", DistributionStatusEnum.DISTRIBUTED); } @@ -442,31 +430,39 @@ public final class AtomicOperationUtils { return addComponentInstanceToComponentContainer(compInstParent, compContainer, UserRoleEnum.DESIGNER, false); } - public static Either addComponentInstanceToComponentContainer(Component compInstParent, Component compContainer, UserRoleEnum userRole, Boolean validateState) { - try { - User defaultUser = ElementFactory.getDefaultUser(userRole); - ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(compInstParent); - RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, defaultUser, compContainer); - - if (validateState) { - if (createComponentInstance.getErrorCode() == ServiceRestUtils.STATUS_CODE_NOT_FOUND) - { - throw new SkipException("Open bug DE262001"); - } - else{ - assertTrue("error - " + createComponentInstance.getErrorCode() + "instead - " + ServiceRestUtils.STATUS_CODE_CREATED, createComponentInstance.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED); - } - } - - if (createComponentInstance.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { - ComponentInstance componentInstance = ResponseParser.convertComponentInstanceResponseToJavaObject(createComponentInstance.getResponse()); - return Either.left(componentInstance); - } - return Either.right(createComponentInstance); - } catch (Exception e) { - throw new AtomicOperationException(e); - } - } + public static Either addComponentInstanceToComponentContainer(Component compInstParent, + Component compContainer, + UserRoleEnum userRole, + Boolean validateState) { + try { + User defaultUser = ElementFactory.getDefaultUser(userRole); + ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(compInstParent); + if (componentInstanceDetails.getOriginType() == null){ + componentInstanceDetails.setOriginType(((Resource) compInstParent).getResourceType().toString()); + } + RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, + defaultUser, compContainer); + + if (validateState) { + if (createComponentInstance.getErrorCode() == ServiceRestUtils.STATUS_CODE_NOT_FOUND) { + throw new SkipException("Open bug DE262001"); + } else { + assertTrue("error - " + createComponentInstance.getErrorCode() + "instead - " + + ServiceRestUtils.STATUS_CODE_CREATED, + createComponentInstance.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED); + } + } + + if (createComponentInstance.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { + ComponentInstance componentInstance = ResponseParser + .convertComponentInstanceResponseToJavaObject(createComponentInstance.getResponse()); + return Either.left(componentInstance); + } + return Either.right(createComponentInstance); + } catch (Exception e) { + throw new AtomicOperationException(e); + } + } public static Either addComponentInstanceToComponentContainer(Component compInstParent, Component compContainer, UserRoleEnum userRole, Boolean validateState, String positionX, String positionY) { try { @@ -607,6 +603,26 @@ public final class AtomicOperationUtils { } + public static Either, RestResponse> updateComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails, User sdncModifierDetails, Component container, boolean validateState) throws Exception { + + RestResponse updateComponentInstance = ComponentInstanceRestUtils.updateComponentInstance(componentInstanceReqDetails, sdncModifierDetails, container.getUniqueId(), container.getComponentType()); + if (validateState) { + assertTrue("Update ComponentInstance failed: " + updateComponentInstance.getResponseMessage(), updateComponentInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + } + if (updateComponentInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) { + String componentType = container.getComponentType().getValue(); + Component componentObject; + if(componentType.equals("Resource")){ + componentObject = getResourceObject(container.getUniqueId()); + }else{ + componentObject = getServiceObject(container.getUniqueId()); + } + ComponentInstance componentInstanceJavaObject = ResponseParser.convertComponentInstanceResponseToJavaObject(updateComponentInstance.getResponse()); + return Either.left(Pair.of(componentObject, componentInstanceJavaObject)); + } + return Either.right(updateComponentInstance); + } + public static Either, RestResponse> changeComponentInstanceVersion(Component containerDetails, ComponentInstance componentInstanceToReplace, Component newInstance, UserRoleEnum userRole, Boolean validateState) throws Exception { User defaultUser = ElementFactory.getDefaultUser(userRole); @@ -627,6 +643,20 @@ public final class AtomicOperationUtils { return Either.right(changeComponentInstanceVersionResp); } + public static ComponentInstance getComponentInstanceByName(Component component, String name) { + ComponentInstance componentInstance = component.getComponentInstances() + .stream() + .filter(ci->ci.getName().equals(name)) + .findFirst() + .orElse(null); + if (componentInstance == null) { + List componentInstancesNameList = component.getComponentInstances().stream().map(ComponentInstance::getName).collect(Collectors.toList()); + assertFalse("Instance name " + name + " not found in container " + component.getComponentType() + " named [" + component.getName() + + "]. Component instances available are: " + componentInstancesNameList.toString(), true); + } + return componentInstance; + } + // *********** PROPERTIES ***************** public static Either addCustomPropertyToResource(PropertyReqDetails propDetails, Resource resourceDetails, UserRoleEnum userRole, Boolean validateState) throws Exception { @@ -1016,4 +1046,13 @@ public final class AtomicOperationUtils { return null; } + public static Pair updateComponentInstanceName(String newName, Component component, String canvasElementName, User user, Boolean validateState) throws Exception { + ComponentInstanceReqDetails componentInstanceReqDetails = ElementFactory.getDefaultComponentInstance(); + ComponentInstance componentInstanceByName = AtomicOperationUtils.getComponentInstanceByName(component, canvasElementName); + componentInstanceReqDetails.setName(newName); + componentInstanceReqDetails.setComponentUid(componentInstanceByName.getComponentUid()); + componentInstanceReqDetails.setUniqueId(componentInstanceByName.getUniqueId()); + return AtomicOperationUtils.updateComponentInstance(componentInstanceReqDetails, user, component, validateState).left().value(); + } + } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java index 44e7b56426..72cad8c3ca 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java @@ -374,13 +374,9 @@ public class LifecycleRestUtils extends BaseRestUtils { // String environmentName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0); DistributionStatusEnum distributionStatusEnum = DistributionStatusEnum.findState(reqDistributionStatus.getValue()); switch(distributionStatusEnum){ - case DISTRIBUTION_APPROVED: - return sendApproveDistribution(user, uniqueId, userRemarks); case DISTRIBUTED: String url = String.format(Urls.ACTIVATE_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId, environmentName); return sendDistrState(user, userRemarks, url); - case DISTRIBUTION_REJECTED: - return rejectDistribution(user, userRemarks, uniqueId); default: return null; diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java index 9bfcfcf962..62d491a3b1 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java @@ -26,7 +26,7 @@ import com.google.gson.JsonParser; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.resources.data.ESArtifactData; +import org.openecomp.sdc.be.resources.data.DAOArtifactData; import org.openecomp.sdc.ci.tests.config.Config; import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; @@ -106,14 +106,14 @@ public class ArtifactValidationUtils { counter); } - public static ESArtifactData parseArtifactRespFromES(RestResponse resResponse) throws Exception { + public static DAOArtifactData parseArtifactRespFromES(RestResponse resResponse) throws Exception { String bodyToParse = resResponse.getResponse(); JsonElement jElement = new JsonParser().parse(bodyToParse); JsonElement jsourceElement = jElement.getAsJsonObject().get("_source"); ObjectMapper mapper = new ObjectMapper(); - return mapper.readValue(jsourceElement.toString(), ESArtifactData.class); + return mapper.readValue(jsourceElement.toString(), DAOArtifactData.class); } @@ -174,13 +174,13 @@ public class ArtifactValidationUtils { } public static void validateEsArtifactReqVsResp(ArtifactReqDetails expectedArtifactInfo, - ESArtifactData esArtifactData) throws Exception { + DAOArtifactData DAOArtifactData) throws Exception { String expectedArtifactUid = expectedArtifactInfo.getUniqueId(); if (expectedArtifactUid == null) expectedArtifactUid = ""; - assertEquals("artifact name is not correct ", expectedArtifactUid, esArtifactData.getId()); + assertEquals("artifact name is not correct ", expectedArtifactUid, DAOArtifactData.getId()); - String actualPayload = Decoder.encode(esArtifactData.getData().array()); + String actualPayload = Decoder.encode(DAOArtifactData.getData().array()); assertEquals("artifact payloadData is not correct ", expectedArtifactInfo.getPayload(), actualPayload); } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/AssetLifeCycle.java b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/AssetLifeCycle.java index abfa37b711..427d3774c1 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/AssetLifeCycle.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/AssetLifeCycle.java @@ -444,26 +444,10 @@ public class AssetLifeCycle extends ComponentBaseTest { @DataProvider(name="invalidStatesForService") public static Object[][] dataProviderInvalidStatesForService() { return new Object[][] { - {LifeCycleStatesEnum.CHECKIN, LifeCycleStatesEnum.CHECKIN, COMPONENT_ALREADY_CHECKED_IN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, "409", ActionStatus.COMPONENT_ALREADY_CHECKED_IN, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), null}, - {LifeCycleStatesEnum.CHECKIN, LifeCycleStatesEnum.STARTCERTIFICATION, COMPONENT_NOT_READY_FOR_CERTIFICATION, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, "403", ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, - {LifeCycleStatesEnum.CHECKIN, LifeCycleStatesEnum.CERTIFY, COMPONENT_NOT_READY_FOR_CERTIFICATION, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, "403", ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, - - {LifeCycleStatesEnum.CHECKOUT, LifeCycleStatesEnum.CHECKOUT, COMPONENT_IN_CHECKOUT_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, "403", ActionStatus.COMPONENT_IN_CHECKOUT_STATE, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), null}, - {LifeCycleStatesEnum.CHECKOUT, LifeCycleStatesEnum.STARTCERTIFICATION, COMPONENT_NOT_READY_FOR_CERTIFICATION, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, "403", ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, - {LifeCycleStatesEnum.CHECKOUT, LifeCycleStatesEnum.CERTIFY, COMPONENT_NOT_READY_FOR_CERTIFICATION, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, "403", ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, - - {LifeCycleStatesEnum.CERTIFICATIONREQUEST, LifeCycleStatesEnum.CERTIFICATIONREQUEST, COMPONENT_SENT_FOR_CERTIFICATION, LifecycleStateEnum.READY_FOR_CERTIFICATION, LifecycleStateEnum.READY_FOR_CERTIFICATION, "403", ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), null}, - {LifeCycleStatesEnum.CERTIFICATIONREQUEST, LifeCycleStatesEnum.CERTIFY, RESTRICTED_OPERATION, LifecycleStateEnum.READY_FOR_CERTIFICATION, LifecycleStateEnum.READY_FOR_CERTIFICATION, "409", ActionStatus.RESTRICTED_OPERATION, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), null}, - - {LifeCycleStatesEnum.STARTCERTIFICATION, LifeCycleStatesEnum.CHECKIN, COMPONENT_IN_CERT_IN_PROGRESS_STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, "403", ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, - {LifeCycleStatesEnum.STARTCERTIFICATION, LifeCycleStatesEnum.CHECKOUT, COMPONENT_IN_CERT_IN_PROGRESS_STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, "403", ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, - {LifeCycleStatesEnum.STARTCERTIFICATION, LifeCycleStatesEnum.CERTIFICATIONREQUEST, COMPONENT_IN_CERT_IN_PROGRESS_STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, "403", ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, - {LifeCycleStatesEnum.STARTCERTIFICATION, LifeCycleStatesEnum.STARTCERTIFICATION, COMPONENT_IN_CERT_IN_PROGRESS_STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, "403", ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, - - {LifeCycleStatesEnum.CERTIFY, LifeCycleStatesEnum.CHECKIN, COMPONENT_ALREADY_CERTIFIED, LifecycleStateEnum.CERTIFIED, LifecycleStateEnum.CERTIFIED, "403", ActionStatus.COMPONENT_ALREADY_CERTIFIED, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, - {LifeCycleStatesEnum.CERTIFY, LifeCycleStatesEnum.CERTIFICATIONREQUEST, COMPONENT_ALREADY_CERTIFIED, LifecycleStateEnum.CERTIFIED, LifecycleStateEnum.CERTIFIED, "403", ActionStatus.COMPONENT_ALREADY_CERTIFIED, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ElementFactory.getDefaultUser(UserRoleEnum.TESTER)}, - {LifeCycleStatesEnum.CERTIFY, LifeCycleStatesEnum.STARTCERTIFICATION, COMPONENT_ALREADY_CERTIFIED, LifecycleStateEnum.CERTIFIED, LifecycleStateEnum.CERTIFIED, "403", ActionStatus.COMPONENT_ALREADY_CERTIFIED, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, - {LifeCycleStatesEnum.CERTIFY, LifeCycleStatesEnum.CERTIFY, COMPONENT_NOT_READY_FOR_CERTIFICATION, LifecycleStateEnum.CERTIFIED, LifecycleStateEnum.CERTIFIED, "403", ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), null}, + {LifeCycleStatesEnum.CHECKIN, LifeCycleStatesEnum.CHECKIN, COMPONENT_ALREADY_CHECKED_IN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, "409", ActionStatus.COMPONENT_ALREADY_CHECKED_IN, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), null}, + {LifeCycleStatesEnum.CHECKOUT, LifeCycleStatesEnum.CHECKOUT, COMPONENT_IN_CHECKOUT_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, "403", ActionStatus.COMPONENT_IN_CHECKOUT_STATE, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), null}, + {LifeCycleStatesEnum.CERTIFY, LifeCycleStatesEnum.CHECKIN, COMPONENT_ALREADY_CERTIFIED, LifecycleStateEnum.CERTIFIED, LifecycleStateEnum.CERTIFIED, "403", ActionStatus.COMPONENT_ALREADY_CERTIFIED, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)}, + {LifeCycleStatesEnum.CERTIFY, LifeCycleStatesEnum.CERTIFY, COMPONENT_NOT_READY_FOR_CERTIFICATION, LifecycleStateEnum.CERTIFIED, LifecycleStateEnum.CERTIFIED, "403", ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), null}, }; } @@ -472,11 +456,7 @@ public class AssetLifeCycle extends ComponentBaseTest { public void invalidStatesForService(LifeCycleStatesEnum initState, LifeCycleStatesEnum targetState, int errorCode, LifecycleStateEnum preState, LifecycleStateEnum currState, String status, ActionStatus actionStatus, User user, User operationUser) throws Exception { - - if(initState.equals(LifeCycleStatesEnum.STARTCERTIFICATION) && targetState.equals(LifeCycleStatesEnum.CHECKIN)){ - throw new SkipException("Open bug DE270217 or TDP number: 154592"); - } - + getExtendTest().log(Status.INFO, String.format("initState: %s, targetState: %s, errorCode: %s," + " preState: %s, currState: %s, status: %s, actionStatus: %s, user: %s, operationUser: %s", initState, targetState, errorCode, preState, currState, status, actionStatus, user, operationUser)); @@ -493,10 +473,6 @@ public class AssetLifeCycle extends ComponentBaseTest { restResponse = LifecycleRestUtils.checkOutService(service.getUUID(), user); } else if(targetState.equals(LifeCycleStatesEnum.CHECKIN)) { restResponse = LifecycleRestUtils.checkInService(service.getUUID(), user); - } else if(targetState.equals(LifeCycleStatesEnum.CERTIFICATIONREQUEST)) { - restResponse = LifecycleRestUtils.certificationRequestService(service.getUUID(), user); - } else if(targetState.equals(LifeCycleStatesEnum.STARTCERTIFICATION)) { - restResponse = LifecycleRestUtils.startTestingService(service.getUUID(), user); } else if(targetState.equals(LifeCycleStatesEnum.CERTIFY)) { restResponse = LifecycleRestUtils.certifyService(service.getUUID(), user); } @@ -540,11 +516,7 @@ public class AssetLifeCycle extends ComponentBaseTest { getExtendTest().log(Status.INFO, String.format("initState: %s, targetState: %s, errorCode: %s," + " preState: %s, currState: %s, status: %s, actionStatus: %s, user: %s, operationUser: %s", initState, targetState, errorCode, preState, currState, status, actionStatus, user, operationUser)); - - if(initState.equals(LifeCycleStatesEnum.STARTCERTIFICATION) && targetState.equals(LifeCycleStatesEnum.CHECKIN)){ - throw new SkipException("Open bug DE270217 or TDP number: 154592"); - } - + Either createdComponent = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true); Component resourceDetails = createdComponent.left().value(); @@ -556,10 +528,6 @@ public class AssetLifeCycle extends ComponentBaseTest { restResponse = LifecycleRestUtils.checkOutResource(resourceDetails.getUUID(), user); } else if(targetState.equals(LifeCycleStatesEnum.CHECKIN)) { restResponse = LifecycleRestUtils.checkInResource(resourceDetails.getUUID(), user); - /*} else if(targetState.equals(LifeCycleStatesEnum.CERTIFICATIONREQUEST)) { - restResponse = LifecycleRestUtils.certificationRequestResource(resourceDetails.getUUID(), user); - } else if(targetState.equals(LifeCycleStatesEnum.STARTCERTIFICATION)) { - restResponse = LifecycleRestUtils.startTestingResource(resourceDetails.getUUID(), user);*/ } else if(targetState.equals(LifeCycleStatesEnum.CERTIFY)) { restResponse = LifecycleRestUtils.certifyResource(resourceDetails.getUUID(), user); } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetFilteredAssetServlet.java b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetFilteredAssetServlet.java index fd230d4943..94d1047ddb 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetFilteredAssetServlet.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetFilteredAssetServlet.java @@ -517,7 +517,7 @@ public class GetFilteredAssetServlet extends ComponentBaseTest { service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); ServiceReqDetails certifyService = new ServiceReqDetails(service); - LifecycleRestUtils.changeDistributionStatus(certifyService, certifyService.getVersion(), ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR), null, DistributionStatusEnum.DISTRIBUTION_APPROVED); + LifecycleRestUtils.changeDistributionStatus(certifyService, certifyService.getVersion(), ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR), null, DistributionStatusEnum.DISTRIBUTED); AtomicOperationUtils.distributeService(service, false); expectedAssetNamesList.add(service.getName()); @@ -529,7 +529,7 @@ public class GetFilteredAssetServlet extends ComponentBaseTest { service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); certifyService = new ServiceReqDetails(service); - LifecycleRestUtils.changeDistributionStatus(certifyService, certifyService.getVersion(), ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR), null, DistributionStatusEnum.DISTRIBUTION_APPROVED); + LifecycleRestUtils.changeDistributionStatus(certifyService, certifyService.getVersion(), ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR), null, DistributionStatusEnum.DISTRIBUTED); AtomicOperationUtils.distributeService(service, false); expectedAssetNamesList.add(service.getName()); diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/AddComponentInstancesArtifactsInCsar.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/AddComponentInstancesArtifactsInCsar.java index 7ea23c1ff3..f71efa2ee3 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/AddComponentInstancesArtifactsInCsar.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/AddComponentInstancesArtifactsInCsar.java @@ -28,10 +28,10 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject; import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/LocalGeneralUtilities.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/LocalGeneralUtilities.java index f5ebac6eeb..01cd57a133 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/LocalGeneralUtilities.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/LocalGeneralUtilities.java @@ -24,9 +24,9 @@ import org.json.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject; import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; import org.openecomp.sdc.ci.tests.pages.HomePage; diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/VfModule.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/VfModule.java index d2c37c2b88..0a7d814572 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/VfModule.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/VfModule.java @@ -23,7 +23,6 @@ package org.openecomp.sdc.ci.tests.US; import com.aventstack.extentreports.Status; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.ci.tests.data.providers.OnboardingDataProviders; -import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; import org.openecomp.sdc.ci.tests.datatypes.CanvasManager; import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.ToscaArtifactsScreenEnum; @@ -31,6 +30,7 @@ import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; import org.openecomp.sdc.ci.tests.datatypes.TypeHeatMetaDefinition; +import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject; import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; import org.openecomp.sdc.ci.tests.execute.devCI.ArtifactFromCsar; @@ -58,7 +58,7 @@ import org.openecomp.sdc.ci.tests.verificator.ServiceVerificator; import org.openecomp.sdc.ci.tests.verificator.VfModuleVerificator; import org.testng.annotations.Test; -import java.awt.AWTException; +import java.awt.*; import java.io.File; import java.util.LinkedList; import java.util.List; diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProvider/OnbordingDataProviders.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProvider/OnbordingDataProviders.java index 89d90df24d..2536e090c5 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProvider/OnbordingDataProviders.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProvider/OnbordingDataProviders.java @@ -20,16 +20,17 @@ package org.openecomp.sdc.ci.tests.dataProvider; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; import org.openecomp.sdc.ci.tests.datatypes.enums.XnfTypeEnum; import org.openecomp.sdc.ci.tests.utilities.FileHandling; import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtils; import org.testng.Assert; import org.testng.annotations.DataProvider; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + public class OnbordingDataProviders { private static final String VSP_VGW_CSAR = "vsp-vgw.csar"; diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java index 0d216572ba..7a8bcd3aba 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java @@ -20,13 +20,14 @@ package org.openecomp.sdc.ci.tests.datatypes; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import org.openecomp.sdc.ci.tests.pages.TopSearchComponent; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + public final class DataTestIdEnum { private DataTestIdEnum() { @@ -101,7 +102,7 @@ public final class DataTestIdEnum { ADD("Add"), DESCRIPTION("description"), SUMBIT_FOR_TESTING_MESSAGE("changeLifeCycleMessage"), - OK("OK"), + OK("confirm-modal-button-ok"), CANCEL("Cancel"), DELETE_INSTANCE_OK("deleteInstanceModal-button-ok"), DELETE_INSTANCE_CANCEL("deleteInstanceModal-button-cancel"), @@ -418,6 +419,8 @@ public final class DataTestIdEnum { DESCRIPTION("description"), CATEGORY("selectGeneralCategory"), PROJECT_CODE("projectCode"), + NAMING_POLICY("namingPolicy"), + SERVICE_FUNCTION("serviceFunction"), TAGS("i-sdc-tag-input"), CONTACT_ID("contactId"), ICON(" iconBox"), @@ -523,7 +526,7 @@ public final class DataTestIdEnum { CHANGE_VERSION("changeVersion", Collections.emptyList()), DEPLOYMENT_ARTIFACT_TAB("deployment-artifact-tab", Collections.singletonList("Deployment Artifacts")), ADD_ARTIFACT("add_Artifact_Button", Collections.emptyList()), - SEARCH_ASSET("searchAsset", Collections.emptyList()), + SEARCH_ASSET("searchAsset-input", Arrays.asList()), PROPERTIES_AND_ATTRIBUTES_TAB("properties-and-attributes-tab", Collections.emptyList()), MENU_INPUTS("sub-menu-button-inputs", Collections.emptyList()), MENU_ONBOARD("sub-menu-button-onboard", Collections.emptyList()), @@ -708,7 +711,7 @@ public final class DataTestIdEnum { @AllArgsConstructor @Getter public enum ImportVfRepository { - SEARCH("onboarding-search"), + SEARCH("onboarding-search-input"), IMPORT_VSP("import-csar"), DOWNLOAD_CSAR("download-csar"), UPDATE_VSP("update-csar"); diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ArchiveRestoreTest.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ArchiveRestoreTest.java index 0e6bfc9dfc..95ee634050 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ArchiveRestoreTest.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ArchiveRestoreTest.java @@ -27,11 +27,11 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; import org.openecomp.sdc.ci.tests.datatypes.TopMenuButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject; import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java index 83e64ef570..a751cc2126 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java @@ -28,9 +28,9 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.ci.tests.dataProvider.OnbordingDataProviders; -import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject; import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardingFlowsThroughAPI.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardingFlowsThroughAPI.java index 136fcb5c07..d2851efc17 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardingFlowsThroughAPI.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardingFlowsThroughAPI.java @@ -28,10 +28,10 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.ci.tests.data.providers.OnboardingDataProviders; -import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; import org.openecomp.sdc.ci.tests.datatypes.TopMenuButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject; import org.openecomp.sdc.ci.tests.datatypes.enums.CvfcTypeEnum; import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardingFlowsUi.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardingFlowsUi.java index 17c953ee13..a3a9d1a9e0 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardingFlowsUi.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardingFlowsUi.java @@ -20,20 +20,11 @@ package org.openecomp.sdc.ci.tests.execute.sanity; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertTrue; -import static org.testng.AssertJUnit.fail; - import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.Status; -import java.io.File; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.ci.tests.data.providers.OnboardingDataProviders; import org.openecomp.sdc.ci.tests.dataProvider.OnbordingDataProviders; import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; @@ -45,7 +36,6 @@ import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject; import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; import org.openecomp.sdc.ci.tests.datatypes.enums.XnfTypeEnum; -import org.openecomp.sdc.ci.tests.execute.setup.ArtifactsCorrelationManager; import org.openecomp.sdc.ci.tests.execute.setup.DriverFactory; import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; @@ -58,7 +48,6 @@ import org.openecomp.sdc.ci.tests.pages.CompositionPage; import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage; import org.openecomp.sdc.ci.tests.pages.GovernorOperationPage; import org.openecomp.sdc.ci.tests.pages.HomePage; -import org.openecomp.sdc.ci.tests.pages.HomePage.PageElement; import org.openecomp.sdc.ci.tests.pages.OpsOperationPage; import org.openecomp.sdc.ci.tests.pages.ResourceCreatePage; import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; @@ -72,6 +61,7 @@ import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; import org.openecomp.sdc.ci.tests.utilities.OnboardingUiUtils; import org.openecomp.sdc.ci.tests.utilities.ServiceUIUtils; import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils; import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtils; import org.openecomp.sdc.ci.tests.utils.general.VendorLicenseModelRestUtils; @@ -87,6 +77,20 @@ import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.openecomp.sdc.ci.tests.pages.GeneralPageElements.clickOKButton; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.fail; + public class OnboardingFlowsUi extends SetupCDTest { private static final Logger LOGGER = LoggerFactory.getLogger(OnboardingFlowsUi.class); @@ -415,28 +419,15 @@ public class OnboardingFlowsUi extends SetupCDTest { ServiceUIUtils.createService(serviceMetadata); ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); - CompositionPage.searchForElement(vspName); - final CanvasManager serviceCanvasManager = CanvasManager.getCanvasManager(); - final CanvasElement vfElement = serviceCanvasManager.createElementOnCanvas(vspName); - ArtifactsCorrelationManager.addVNFtoServiceArtifactCorrelation(serviceMetadata.getName(), vspName); - - assertNotNull(vfElement); - ServiceVerificator.verifyNumOfComponentInstances(serviceMetadata, "0.1", 1, getUser()); - ExtentTestActions.addScreenshot(Status.INFO, "ServiceComposition_" + vnfFile, "The service topology is as follows: "); - - ServiceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); - - reloginWithNewRole(UserRoleEnum.TESTER); - GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); - TesterOperationPage.certifyComponent(serviceMetadata.getName()); - - reloginWithNewRole(UserRoleEnum.GOVERNOR); - HomePage.waitForElement(PageElement.COMPONENT_PANEL); - HomePage.findComponentAndClick(serviceMetadata.getName()); - GovernorOperationPage.approveService(serviceMetadata.getName()); + Service containerObject = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, serviceMetadata.getName(), "0.1"); + Resource instanceObject = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vspName, "1.0"); + ComponentInstance componentInstanceDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(instanceObject, containerObject, UserRoleEnum.DESIGNER, true).left().value(); - runDistributionFlow(serviceMetadata); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.LifeCyleChangeButtons.CERTIFY.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DistributionChangeButtons.APPROVE_MESSAGE.getValue()) + .sendKeys("service " + serviceMetadata.getName() + " certified successfully"); + clickOKButton(); getExtendTest().log(Status.INFO, String.format("Successfully onboarded the package '%s'", vnfFile)); } diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PropertiesAssignmentUpdateFlow.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PropertiesAssignmentUpdateFlow.java index ec2b88dbf9..41c0d406b7 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PropertiesAssignmentUpdateFlow.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PropertiesAssignmentUpdateFlow.java @@ -27,13 +27,13 @@ import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; import org.openecomp.sdc.ci.tests.datatypes.CanvasManager; import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; import org.openecomp.sdc.ci.tests.datatypes.TopMenuButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject; import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PropertiesAssignmentUpdateFlow_New.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PropertiesAssignmentUpdateFlow_New.java index 92123f66d6..c4b17f6594 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PropertiesAssignmentUpdateFlow_New.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PropertiesAssignmentUpdateFlow_New.java @@ -26,13 +26,13 @@ import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; import org.openecomp.sdc.ci.tests.datatypes.CanvasManager; import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; import org.openecomp.sdc.ci.tests.datatypes.TopMenuButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject; import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java index 530c3fba96..fc4dd88185 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java @@ -73,7 +73,7 @@ import org.testng.TestException; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import java.awt.AWTException; +import java.awt.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/UpgradeServices.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/UpgradeServices.java index 9fc4cd7243..d8266f19df 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/UpgradeServices.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/UpgradeServices.java @@ -25,7 +25,6 @@ import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; import org.openecomp.sdc.ci.tests.datatypes.CanvasManager; import org.openecomp.sdc.ci.tests.datatypes.ConnectionWizardPopUpObject; @@ -36,6 +35,7 @@ import org.openecomp.sdc.ci.tests.datatypes.PortMirroringEnum; import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; import org.openecomp.sdc.ci.tests.datatypes.TopMenuButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject; import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java index 56b6fb7f17..9ee8c06938 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java @@ -23,9 +23,9 @@ package org.openecomp.sdc.ci.tests.execute.sanity; import com.aventstack.extentreports.Status; import org.apache.http.HttpStatus; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject; import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum; diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java index 6a1ec57837..51f78f9eb3 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java @@ -20,15 +20,10 @@ package org.openecomp.sdc.ci.tests.execute.sanity; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - import com.aventstack.extentreports.Status; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo; @@ -76,6 +71,12 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + public class Vf extends SetupCDTest { private static final Logger LOGGER = LoggerFactory.getLogger(Vf.class); @@ -426,15 +427,16 @@ public class Vf extends SetupCDTest { } @Test - public void changeInstanceNameInVfTest() { + public void changeInstanceNameInVfTest() throws Exception { final ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); ResourceUIUtils.createVF(vfMetaData, getUser()); + Resource containerObject = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vfMetaData.getName(), vfMetaData.getVersion()); + Resource computeObject = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, "Compute", "1.0"); + ComponentInstance componentInstanceDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(computeObject, containerObject, UserRoleEnum.DESIGNER, true).left().value(); + containerObject = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vfMetaData.getName(), vfMetaData.getVersion()); + String intanceWithUpdatedName = AtomicOperationUtils.updateComponentInstanceName("newName", containerObject, componentInstanceDetails.getName(), getUser(), true).getRight().getName(); ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); - final CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); - final CanvasElement computeElement = vfCanvasManager.createElementOnCanvas(LeftPanelCanvasItems.COMPUTE); - final String updatedInstanceName = "updatedName"; - vfCanvasManager.updateElementNameInCanvas(computeElement, updatedInstanceName); - assertEquals(CompositionPage.getSelectedInstanceName(), updatedInstanceName); + assertEquals(intanceWithUpdatedName, "newName"); } @Test diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentTestActions.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentTestActions.java index 4fc05d93a8..d05d3c5498 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentTestActions.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentTestActions.java @@ -26,15 +26,15 @@ import com.aventstack.extentreports.Status; import com.aventstack.extentreports.markuputils.ExtentColor; import com.aventstack.extentreports.markuputils.Markup; import com.aventstack.extentreports.markuputils.MarkupHelper; -import java.util.Optional; import org.openecomp.sdc.ci.tests.api.SomeInterface; import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; +import java.util.Optional; import java.util.UUID; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public final class ExtentTestActions { diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentTestManager.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentTestManager.java index 1effea93b8..669cbe17ef 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentTestManager.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentTestManager.java @@ -22,9 +22,10 @@ package org.openecomp.sdc.ci.tests.execute.setup; import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTest; -import java.util.HashMap; import org.openecomp.sdc.ci.tests.api.SomeInterface; +import java.util.HashMap; + public class ExtentTestManager implements SomeInterface { private final HashMap extentTestByThreadIdMap = new HashMap<>(); diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ReportAfterTestManager.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ReportAfterTestManager.java index 50b6dafe1a..e35ba05004 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ReportAfterTestManager.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ReportAfterTestManager.java @@ -20,12 +20,7 @@ package org.openecomp.sdc.ci.tests.execute.setup; -import static org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions.addScreenshot; -import static org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions.addTag; -import static org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions.log; - import com.aventstack.extentreports.Status; -import java.io.IOException; import org.apache.commons.lang3.StringUtils; import org.openecomp.sdc.ci.tests.execute.setup.ExtentManager.suiteNameXml; import org.slf4j.Logger; @@ -33,6 +28,12 @@ import org.slf4j.LoggerFactory; import org.testng.ITestContext; import org.testng.ITestResult; +import java.io.IOException; + +import static org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions.addScreenshot; +import static org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions.addTag; +import static org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions.log; + public class ReportAfterTestManager { private static final Logger LOGGER = LoggerFactory.getLogger(ReportAfterTestManager.class); diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/WebDriverThread.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/WebDriverThread.java index 8fdad16497..6118fa2fee 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/WebDriverThread.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/WebDriverThread.java @@ -35,13 +35,13 @@ import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.LocalFileDetector; import org.openqa.selenium.remote.RemoteWebDriver; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.UUID; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class WebDriverThread { diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/CheckSoftwareVersionPropertyFlow.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/CheckSoftwareVersionPropertyFlow.java index dbdbe10c6d..c91f89370d 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/CheckSoftwareVersionPropertyFlow.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/CheckSoftwareVersionPropertyFlow.java @@ -19,18 +19,19 @@ package org.openecomp.sdc.ci.tests.flow; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertThat; - import com.aventstack.extentreports.Status; -import java.util.List; -import java.util.Optional; import org.openecomp.sdc.ci.tests.pages.PageObject; import org.openecomp.sdc.ci.tests.pages.ResourceLeftSideMenu; import org.openecomp.sdc.ci.tests.pages.ResourcePropertiesAssignmentPage; import org.openqa.selenium.WebDriver; +import java.util.List; +import java.util.Optional; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.Assert.assertThat; + /** * UI Flow for checking the software version property in a resource */ diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/CreateResourceFlow.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/CreateResourceFlow.java index 0ff923c42a..65d55993f0 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/CreateResourceFlow.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/CreateResourceFlow.java @@ -20,12 +20,13 @@ package org.openecomp.sdc.ci.tests.flow; import com.aventstack.extentreports.Status; -import java.util.Optional; import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; import org.openecomp.sdc.ci.tests.pages.PageObject; import org.openecomp.sdc.ci.tests.pages.ResourceCreatePage; import org.openqa.selenium.WebDriver; +import java.util.Optional; + /** * UI Flow for Resource creation */ diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/CreateVspFlow.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/CreateVspFlow.java index 910ef4d4ed..b5af962243 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/CreateVspFlow.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/CreateVspFlow.java @@ -19,11 +19,7 @@ package org.openecomp.sdc.ci.tests.flow; -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - import com.aventstack.extentreports.Status; -import java.util.Optional; import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; import org.openecomp.sdc.ci.tests.pages.OnboardHomePage; import org.openecomp.sdc.ci.tests.pages.PageObject; @@ -33,6 +29,11 @@ import org.openecomp.sdc.ci.tests.pages.VspCreationModal; import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; import org.openqa.selenium.WebDriver; +import java.util.Optional; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; + /** * UI Flow for VSP creation */ diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/ImportVspFlow.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/ImportVspFlow.java index e59a5c179c..5d05479b41 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/ImportVspFlow.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/ImportVspFlow.java @@ -20,7 +20,6 @@ package org.openecomp.sdc.ci.tests.flow; import com.aventstack.extentreports.Status; -import java.util.Optional; import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; import org.openecomp.sdc.ci.tests.pages.PageObject; import org.openecomp.sdc.ci.tests.pages.ResourceCreatePage; @@ -28,6 +27,8 @@ import org.openecomp.sdc.ci.tests.pages.TopNavComponent; import org.openecomp.sdc.ci.tests.pages.VspRepositoryModalComponent; import org.openqa.selenium.WebDriver; +import java.util.Optional; + /** * UI Flow for importing a VSP */ diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/UiTestFlow.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/UiTestFlow.java index eedecbfd61..c323479833 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/UiTestFlow.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/flow/UiTestFlow.java @@ -19,9 +19,10 @@ package org.openecomp.sdc.ci.tests.flow; -import java.util.Optional; import org.openecomp.sdc.ci.tests.pages.PageObject; +import java.util.Optional; + /** * Represents a UI test flow */ diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/AbstractPageObject.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/AbstractPageObject.java index 1c051db087..c9b4f4994d 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/AbstractPageObject.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/AbstractPageObject.java @@ -19,13 +19,14 @@ package org.openecomp.sdc.ci.tests.pages; -import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; +import java.util.List; + /** * Base UI test object that represents a page or component in a html page */ diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/DeploymentArtifactPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/DeploymentArtifactPage.java index 669a79ac39..bc0165bb5f 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/DeploymentArtifactPage.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/DeploymentArtifactPage.java @@ -168,7 +168,7 @@ public class DeploymentArtifactPage extends GeneralPageElements { SetupCDTest.getExtendTest().log(Status.INFO, "Verifying the artifacts in the table"); List artifactList = Lists.newArrayList(artifactsFromZipFile).stream().filter(p -> !p.contains(".env")).map(p -> getVisualArtifactName(p)).collect(Collectors.toList()); try { - List rows = GeneralUIUtils.getElementsByCSS("div div[data-tests-id^='artifact-item'] span[data-tests-id^='artifactDisplayName']"); + List rows = GeneralUIUtils.getWebElementsListByContainsClassName("datatable-body-row"); for (WebElement r : rows) { String artifactDisplayed = r.getAttribute("textContent").trim(); if (artifactList.contains(artifactDisplayed)) { diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GeneralPageElements.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GeneralPageElements.java index 611c24a2a5..0342661232 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GeneralPageElements.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GeneralPageElements.java @@ -149,10 +149,12 @@ public class GeneralPageElements { GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DistributionChangeButtons.APPROVE_MESSAGE.getValue()) .sendKeys("resource " + componentName + " certified successfully"); clickOKButton(); - clickUpgradeServicesCloseButton(); + GeneralUIUtils.ultimateWait(); + HomePage.navigateToHomePage(); GeneralUIUtils.ultimateWait(); HomePage.navigateToHomePage(); GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue(), GeneralUIUtils.getTimeOut() / WAIT_FOR_ELEMENT_TIME_OUT_DIVIDER); + GeneralUIUtils.ultimateWait(); } catch (Exception e) { throw new Exception("Certification of " + componentName + " failed"); } @@ -231,7 +233,7 @@ public class GeneralPageElements { public static List getElementsFromTable() { GeneralUIUtils.ultimateWait(); - return GeneralUIUtils.getElementsByLocator(By.className("flex-container")); + return GeneralUIUtils.getElementsByLocator(By.className("datatable-body")); } public static boolean checkElementsCountInTable(int expectedElementsCount) { diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GovernorOperationPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GovernorOperationPage.java index 5ffd6c80a7..d4c0c9054b 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GovernorOperationPage.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/GovernorOperationPage.java @@ -21,7 +21,6 @@ package org.openecomp.sdc.ci.tests.pages; import com.aventstack.extentreports.Status; -import java.io.IOException; import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; @@ -29,6 +28,8 @@ import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; + public class GovernorOperationPage { private static final Logger LOGGER = LoggerFactory.getLogger(GovernorOperationPage.class); diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/HomePage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/HomePage.java index 3454c202a6..a0747fce0b 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/HomePage.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/HomePage.java @@ -20,16 +20,7 @@ package org.openecomp.sdc.ci.tests.pages; -import static org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest.getExtendTest; -import static org.openecomp.sdc.ci.tests.pages.HomePage.PageElement.REPOSITORY_ICON; - import com.aventstack.extentreports.Status; -import java.io.File; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.List; -import java.util.UUID; import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; import org.openecomp.sdc.ci.tests.exception.HomePageRuntimeException; import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; @@ -43,6 +34,16 @@ import org.openqa.selenium.support.ui.WebDriverWait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.List; +import java.util.UUID; + +import static org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest.getExtendTest; +import static org.openecomp.sdc.ci.tests.pages.HomePage.PageElement.REPOSITORY_ICON; + public class HomePage { private static final Logger LOGGER = LoggerFactory.getLogger(HomePage.class); @@ -60,6 +61,7 @@ public class HomePage { } public static boolean searchForVSP(String vspName) { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ImportVfRepository.SEARCH.getValue()).clear(); GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ImportVfRepository.SEARCH.getValue()).sendKeys(vspName); GeneralUIUtils.ultimateWait(); return true; diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/OnboardHeaderComponent.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/OnboardHeaderComponent.java index 5e82f769c1..f5801ad70f 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/OnboardHeaderComponent.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/OnboardHeaderComponent.java @@ -19,15 +19,15 @@ package org.openecomp.sdc.ci.tests.pages; -import static org.openecomp.sdc.ci.tests.pages.OnboardHeaderComponent.XpathSelector.MAIN_DIV; -import static org.openecomp.sdc.ci.tests.pages.OnboardHeaderComponent.XpathSelector.ONBOARD_TAB_DIV; -import static org.openecomp.sdc.ci.tests.pages.OnboardHeaderComponent.XpathSelector.WORKSPACE_TAB_DIV; - import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; +import static org.openecomp.sdc.ci.tests.pages.OnboardHeaderComponent.XpathSelector.MAIN_DIV; +import static org.openecomp.sdc.ci.tests.pages.OnboardHeaderComponent.XpathSelector.ONBOARD_TAB_DIV; +import static org.openecomp.sdc.ci.tests.pages.OnboardHeaderComponent.XpathSelector.WORKSPACE_TAB_DIV; + /** * Handles the Onboard Header Component UI test actions */ diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/OnboardHomePage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/OnboardHomePage.java index 22e4c17f17..3acb34b6c6 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/OnboardHomePage.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/OnboardHomePage.java @@ -19,14 +19,14 @@ package org.openecomp.sdc.ci.tests.pages; -import static org.openecomp.sdc.ci.tests.pages.OnboardHomePage.XpathSelector.ADD_NEW_VLM_BTN; -import static org.openecomp.sdc.ci.tests.pages.OnboardHomePage.XpathSelector.ADD_NEW_VSP_BTN; - import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; +import static org.openecomp.sdc.ci.tests.pages.OnboardHomePage.XpathSelector.ADD_NEW_VLM_BTN; +import static org.openecomp.sdc.ci.tests.pages.OnboardHomePage.XpathSelector.ADD_NEW_VSP_BTN; + /** * Handles the Onboard Home Page UI test actions */ diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertiesAssignmentPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertiesAssignmentPage.java index a90f4632c3..629753f077 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertiesAssignmentPage.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertiesAssignmentPage.java @@ -124,7 +124,7 @@ public class PropertiesAssignmentPage { try { SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on the %s component in Properties", resourceName)); - GeneralUIUtils.clickOnElementChildByTestIdWithoutWait(resourceName); + GeneralUIUtils.clickOnElementByInputTestIdWithoutWait(resourceName); GeneralUIUtils.ultimateWait(); GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue()); } catch (final Exception e) { diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceCreatePage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceCreatePage.java index 5c9ec97ebd..26b3d6f0c6 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceCreatePage.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceCreatePage.java @@ -19,11 +19,6 @@ package org.openecomp.sdc.ci.tests.pages; -import static org.hamcrest.Matchers.equalToIgnoringCase; -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; -import static org.openecomp.sdc.ci.tests.pages.ResourceCreatePage.XpathSelector.FORM_LIFE_CYCLE_STATE; - import org.openecomp.sdc.ci.tests.datatypes.LifeCycleStateEnum; import org.openecomp.sdc.ci.tests.utilities.LoaderHelper; import org.openecomp.sdc.ci.tests.utilities.NotificationHelper; @@ -35,6 +30,11 @@ import org.openqa.selenium.support.ui.ExpectedConditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.hamcrest.Matchers.equalToIgnoringCase; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; +import static org.openecomp.sdc.ci.tests.pages.ResourceCreatePage.XpathSelector.FORM_LIFE_CYCLE_STATE; + /** * Handles the Resource Create Page UI actions */ diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceLeftSideMenu.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceLeftSideMenu.java index 5153107600..fd2f06a9b7 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceLeftSideMenu.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourceLeftSideMenu.java @@ -19,14 +19,14 @@ package org.openecomp.sdc.ci.tests.pages; -import static org.openecomp.sdc.ci.tests.pages.ResourceLeftSideMenu.XpathSelector.MAIN_DIV; -import static org.openecomp.sdc.ci.tests.pages.ResourceLeftSideMenu.XpathSelector.PROPERTIES_ASSIGNMENT_MENU; - import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; +import static org.openecomp.sdc.ci.tests.pages.ResourceLeftSideMenu.XpathSelector.MAIN_DIV; +import static org.openecomp.sdc.ci.tests.pages.ResourceLeftSideMenu.XpathSelector.PROPERTIES_ASSIGNMENT_MENU; + /** * Handles the Resource Page Left Side Menu UI actions */ diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourcePropertiesAssignmentPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourcePropertiesAssignmentPage.java index 433d79e7b4..4cbac6ec92 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourcePropertiesAssignmentPage.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ResourcePropertiesAssignmentPage.java @@ -19,6 +19,14 @@ package org.openecomp.sdc.ci.tests.pages; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; + +import java.util.ArrayList; +import java.util.List; + import static org.openecomp.sdc.ci.tests.pages.ResourcePropertiesAssignmentPage.XpathSelector.MAIN_DIV; import static org.openecomp.sdc.ci.tests.pages.ResourcePropertiesAssignmentPage.XpathSelector.NO_DATA_MESSAGE; import static org.openecomp.sdc.ci.tests.pages.ResourcePropertiesAssignmentPage.XpathSelector.PROPERTIES_TABLE; @@ -26,13 +34,6 @@ import static org.openecomp.sdc.ci.tests.pages.ResourcePropertiesAssignmentPage. import static org.openecomp.sdc.ci.tests.pages.ResourcePropertiesAssignmentPage.XpathSelector.SOFTWARE_VERSION_PROPERTY_CHECKBOX; import static org.openecomp.sdc.ci.tests.pages.ResourcePropertiesAssignmentPage.XpathSelector.TITLE_DIV; -import java.util.ArrayList; -import java.util.List; -import org.openqa.selenium.By; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.support.ui.ExpectedConditions; - /** * Handles the Resource Properties Assignment Page UI actions */ diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ServiceGeneralPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ServiceGeneralPage.java index 07f3f23215..08bd580fc7 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ServiceGeneralPage.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/ServiceGeneralPage.java @@ -55,12 +55,39 @@ public class ServiceGeneralPage extends ResourceGeneralPage { serviceNameTextbox.sendKeys(serviceName); } + + public static void defineServiceFunction(String serviceFunction) { + WebElement serviceFunctionTextbox = GeneralUIUtils + .getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.SERVICE_FUNCTION.getValue()); + serviceFunctionTextbox.clear(); + serviceFunctionTextbox.sendKeys(serviceFunction); + } + public static void defineProjectCode(String pmat) { WebElement projectCodeTextbox = GeneralUIUtils .getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.PROJECT_CODE.getValue()); projectCodeTextbox.clear(); projectCodeTextbox.sendKeys(pmat); } + public static void defineNamingPolicy(String namingPolicyText) { + WebElement namingPolicyTextbox = GeneralUIUtils + .getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.NAMING_POLICY.getValue()); + namingPolicyTextbox.clear(); + namingPolicyTextbox.sendKeys(namingPolicyText); + } + + public static String getServiceFunctionText(){ + return getServiceFunctionField().getAttribute("value"); + } + + public static String getNamingPolicyText(){ + return getNamingPolicyField().getAttribute("value"); + } + + private static WebElement getNamingPolicyField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.NAMING_POLICY.getValue()); + } + public static String getProjectCodeText() { return getProjectCodeField().getAttribute("value"); @@ -69,6 +96,9 @@ public class ServiceGeneralPage extends ResourceGeneralPage { public static String[] getTags() { return ResourceGeneralPage.getElementsFromTagsTable().stream().map(WebElement::getText).toArray(String[]::new); } + private static WebElement getServiceFunctionField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.SERVICE_FUNCTION.getValue()); + } private static WebElement getProjectCodeField() { return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.PROJECT_CODE.getValue()); diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/SoftwareProductOnboarding.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/SoftwareProductOnboarding.java index 169ded44ad..10f493e9c6 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/SoftwareProductOnboarding.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/SoftwareProductOnboarding.java @@ -19,6 +19,12 @@ package org.openecomp.sdc.ci.tests.pages; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.openecomp.sdc.ci.tests.pages.SoftwareProductOnboarding.XpathSelector.ATTACHMENT_VIEW; @@ -30,12 +36,6 @@ import static org.openecomp.sdc.ci.tests.pages.SoftwareProductOnboarding.XpathSe import static org.openecomp.sdc.ci.tests.pages.SoftwareProductOnboarding.XpathSelector.PAGE_MAIN_DIV; import static org.openecomp.sdc.ci.tests.pages.SoftwareProductOnboarding.XpathSelector.SELECTED_NAV_BAR_GROUP_ITEM; -import org.openqa.selenium.By; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebElement; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class SoftwareProductOnboarding extends AbstractPageObject { private static final Logger LOGGER = LoggerFactory.getLogger(SoftwareProductOnboarding.class); diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/TopNavComponent.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/TopNavComponent.java index d16270ff54..acac74fbd2 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/TopNavComponent.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/TopNavComponent.java @@ -19,13 +19,6 @@ package org.openecomp.sdc.ci.tests.pages; -import static org.openecomp.sdc.ci.tests.pages.TopNavComponent.XpathSelector.ARROW_DROPDOWN; -import static org.openecomp.sdc.ci.tests.pages.TopNavComponent.XpathSelector.MAIN_MENU_ONBOARD_BTN; -import static org.openecomp.sdc.ci.tests.pages.TopNavComponent.XpathSelector.NAV; -import static org.openecomp.sdc.ci.tests.pages.TopNavComponent.XpathSelector.REPOSITORY_ICON; -import static org.openecomp.sdc.ci.tests.pages.TopNavComponent.XpathSelector.SUB_MENU_BUTTON_HOME; - -import java.util.List; import org.openecomp.sdc.ci.tests.execute.setup.DriverFactory; import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; import org.openqa.selenium.By; @@ -36,6 +29,14 @@ import org.openqa.selenium.support.ui.ExpectedConditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; + +import static org.openecomp.sdc.ci.tests.pages.TopNavComponent.XpathSelector.ARROW_DROPDOWN; +import static org.openecomp.sdc.ci.tests.pages.TopNavComponent.XpathSelector.MAIN_MENU_ONBOARD_BTN; +import static org.openecomp.sdc.ci.tests.pages.TopNavComponent.XpathSelector.NAV; +import static org.openecomp.sdc.ci.tests.pages.TopNavComponent.XpathSelector.REPOSITORY_ICON; +import static org.openecomp.sdc.ci.tests.pages.TopNavComponent.XpathSelector.SUB_MENU_BUTTON_HOME; + /** * Handles the Top Navigation Component UI actions */ diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/VspCommitModal.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/VspCommitModal.java index 7a6aa7f055..48082f959f 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/VspCommitModal.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/VspCommitModal.java @@ -19,12 +19,6 @@ package org.openecomp.sdc.ci.tests.pages; -import static org.openecomp.sdc.ci.tests.pages.VspCommitModal.XpathSelector.COMMIT_AND_SUBMIT_BTN; -import static org.openecomp.sdc.ci.tests.pages.VspCommitModal.XpathSelector.COMMIT_COMMENT_TXT; -import static org.openecomp.sdc.ci.tests.pages.VspCommitModal.XpathSelector.MODAL_CANCEL_BTN; -import static org.openecomp.sdc.ci.tests.pages.VspCommitModal.XpathSelector.MODAL_DIV; -import static org.openecomp.sdc.ci.tests.pages.VspCommitModal.XpathSelector.SUCCESS_MODAL_DIV; - import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; @@ -32,6 +26,12 @@ import org.openqa.selenium.support.ui.ExpectedConditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.openecomp.sdc.ci.tests.pages.VspCommitModal.XpathSelector.COMMIT_AND_SUBMIT_BTN; +import static org.openecomp.sdc.ci.tests.pages.VspCommitModal.XpathSelector.COMMIT_COMMENT_TXT; +import static org.openecomp.sdc.ci.tests.pages.VspCommitModal.XpathSelector.MODAL_CANCEL_BTN; +import static org.openecomp.sdc.ci.tests.pages.VspCommitModal.XpathSelector.MODAL_DIV; +import static org.openecomp.sdc.ci.tests.pages.VspCommitModal.XpathSelector.SUCCESS_MODAL_DIV; + /** * Handles the VSP Commit Modal UI actions */ diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/VspCreationModal.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/VspCreationModal.java index efd26b9a06..c4540c748d 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/VspCreationModal.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/VspCreationModal.java @@ -19,9 +19,6 @@ package org.openecomp.sdc.ci.tests.pages; -import static org.openecomp.sdc.ci.tests.pages.VspCreationModal.XpathSelector.METHOD_RADIO; -import static org.openecomp.sdc.ci.tests.pages.VspCreationModal.XpathSelector.MODAL_XPATH; - import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; @@ -29,6 +26,9 @@ import org.openqa.selenium.support.ui.Select; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.openecomp.sdc.ci.tests.pages.VspCreationModal.XpathSelector.METHOD_RADIO; +import static org.openecomp.sdc.ci.tests.pages.VspCreationModal.XpathSelector.MODAL_XPATH; + /** * Handles the VSP Creation Modal UI actions */ diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/VspRepositoryModalComponent.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/VspRepositoryModalComponent.java index b7611c69e5..f610074a55 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/VspRepositoryModalComponent.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/VspRepositoryModalComponent.java @@ -19,16 +19,6 @@ package org.openecomp.sdc.ci.tests.pages; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsNot.not; -import static org.junit.Assert.assertThat; -import static org.openecomp.sdc.ci.tests.pages.VspRepositoryModalComponent.XpathSelector.IMPORT_VSP_BTN; -import static org.openecomp.sdc.ci.tests.pages.VspRepositoryModalComponent.XpathSelector.MODAL_DIV; -import static org.openecomp.sdc.ci.tests.pages.VspRepositoryModalComponent.XpathSelector.RESULTS_CONTAINER_DIV; -import static org.openecomp.sdc.ci.tests.pages.VspRepositoryModalComponent.XpathSelector.SEARCH_TXT; - -import java.util.List; import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils; import org.openecomp.sdc.ci.tests.utilities.LoaderHelper; import org.openecomp.sdc.ci.tests.utilities.NotificationHelper; @@ -38,6 +28,17 @@ import org.openqa.selenium.WebElement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; + +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsNot.not; +import static org.junit.Assert.assertThat; +import static org.openecomp.sdc.ci.tests.pages.VspRepositoryModalComponent.XpathSelector.IMPORT_VSP_BTN; +import static org.openecomp.sdc.ci.tests.pages.VspRepositoryModalComponent.XpathSelector.MODAL_DIV; +import static org.openecomp.sdc.ci.tests.pages.VspRepositoryModalComponent.XpathSelector.RESULTS_CONTAINER_DIV; +import static org.openecomp.sdc.ci.tests.pages.VspRepositoryModalComponent.XpathSelector.SEARCH_TXT; + /** * Handles the VSP Repository Modal UI actions */ diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/VspValidationPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/VspValidationPage.java index 12b5251e81..9fa278b1e0 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/VspValidationPage.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/VspValidationPage.java @@ -17,8 +17,6 @@ package org.openecomp.sdc.ci.tests.pages; import com.aventstack.extentreports.Status; -import java.io.File; -import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; @@ -27,6 +25,9 @@ import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.testng.Assert; +import java.io.File; +import java.util.List; + public class VspValidationPage extends GeneralPageElements { private VspValidationPage() { diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/DownloadManager.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/DownloadManager.java index a88f7267d8..88efa26681 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/DownloadManager.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/DownloadManager.java @@ -52,7 +52,7 @@ public class DownloadManager { if (vspFound) { ExtentTestActions.log(Status.INFO, String.format("Going to downloading VSP %s", vspName)); final List elementsFromTable = GeneralPageElements.getElementsFromTable(); - elementsFromTable.get(1).click(); + elementsFromTable.get(0).click(); GeneralUIUtils.waitForLoader(); GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.DOWNLOAD_CSAR.getValue()); ExtentTestActions.log(Status.INFO, "Succeeded to downloaded CSAR file named " + vspName + " into folder " + SetupCDTest.getWindowTest().getDownloadDirectory()); diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java index ef91c1cbb3..d4766c9bba 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java @@ -25,6 +25,7 @@ import org.apache.commons.io.FileUtils; import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; import org.openecomp.sdc.ci.tests.exception.GeneralUiRuntimeException; import org.openecomp.sdc.ci.tests.execute.setup.DriverFactory; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; import org.openecomp.sdc.ci.tests.pages.HomePage; import org.openecomp.sdc.ci.tests.utils.Utils; import org.openqa.selenium.By; @@ -40,8 +41,10 @@ import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.awt.Toolkit; +import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.io.File; @@ -51,8 +54,6 @@ import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import static org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest.getExtendTest; import static org.testng.AssertJUnit.assertTrue; @@ -62,7 +63,7 @@ public final class GeneralUIUtils { private static final Logger LOGGER = LoggerFactory.getLogger(GeneralUIUtils.class); - private static final String DATA_TESTS_ID = "//*[@data-tests-id='%1$s' or @data-test-id='%1$s']"; + private static final String DATA_TESTS_ID = "//*[@data-tests-id='"; private static final String COLOR_YELLOW_BORDER_4PX_SOLID_YELLOW = "color: yellow; border: 4px solid yellow;"; private static final int TIME_OUT = (int) (60 * 1.5); @@ -117,13 +118,18 @@ public final class GeneralUIUtils { } public static WebElement getWebElementByTestID(final String dataTestId, final int timeout) { - final WebDriverWait wait = new WebDriverWait(getDriver(), timeout); - return wait - .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(String.format(DATA_TESTS_ID, dataTestId)))); + try { + final WebDriverWait wait = new WebDriverWait(getDriver(), timeout); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(String.format(DATA_TESTS_ID, dataTestId, "']")))); + } + catch (Exception e) { + System.out.println("Element with dataTestId name: "+dataTestId+" not found"); + return null; + } } public static boolean isWebElementExistByTestId(String dataTestId) { - return getDriver().findElements(By.xpath(String.format(DATA_TESTS_ID, dataTestId))).size() != 0; + return getDriver().findElements(By.xpath(String.format(DATA_TESTS_ID, dataTestId, "']"))).size() != 0; } public static boolean isWebElementExistByClass(String className) { @@ -133,7 +139,7 @@ public final class GeneralUIUtils { public static WebElement getInputElement(String dataTestId) { try { ultimateWait(); - return getDriver().findElement(By.xpath(String.format(DATA_TESTS_ID, dataTestId))); + return getDriver().findElement(By.xpath(String.format(DATA_TESTS_ID, dataTestId, "']"))); } catch (Exception e) { return null; } @@ -141,7 +147,7 @@ public final class GeneralUIUtils { public static List getInputElements(String dataTestId) { ultimateWait(); - return getDriver().findElements(By.xpath(String.format(DATA_TESTS_ID, dataTestId))); + return getDriver().findElements(By.xpath(String.format(DATA_TESTS_ID, dataTestId, "']"))); } @@ -179,7 +185,7 @@ public final class GeneralUIUtils { public static List getWebElementsListByContainTestID(String dataTestId) { try { WebDriverWait wait = new WebDriverWait(getDriver(), WEB_DRIVER_WAIT_TIME_OUT); - return wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(String.format("//*[contains(@data-tests-id, '%1$s') or contains(@data-test-id, '%1$s')]", dataTestId)))); + return wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(String.format("//*[contains(@data-tests-id, '", dataTestId, "')]")))); } catch (Exception e) { return new ArrayList(); } @@ -201,7 +207,7 @@ public final class GeneralUIUtils { public static List getWebElementsListByTestID(String dataTestId) { WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); - return wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath(String.format(DATA_TESTS_ID, dataTestId)))); + return wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath(String.format(DATA_TESTS_ID, dataTestId, "']")))); } public static List getWebElementsListByClassName(String className) { @@ -213,50 +219,68 @@ public final class GeneralUIUtils { public static Boolean isElementInvisibleByTestId(String dataTestId) { WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); return wait.until( - ExpectedConditions.invisibilityOfElementLocated(By.xpath(String.format(DATA_TESTS_ID, dataTestId)))); + ExpectedConditions.invisibilityOfElementLocated(By.xpath(String.format(DATA_TESTS_ID, dataTestId, "']")))); } public static Boolean isElementVisibleByTestId(String dataTestId) { try { WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); - return wait.until(ExpectedConditions.visibilityOfElementLocated((By.xpath(String.format(DATA_TESTS_ID, dataTestId))))).isDisplayed(); + return wait.until(ExpectedConditions.visibilityOfElementLocated((By.xpath(String.format(DATA_TESTS_ID, dataTestId, "']"))))).isDisplayed(); } catch (Exception e) { return false; } } public static void clickOnElementByTestId(String dataTestId) { - LOGGER.debug("Clicking on the element by test id " + dataTestId); - clickOnElementByTestIdWithoutWait(dataTestId); - LOGGER.debug("Waiting after clicking element by test id " + dataTestId); - ultimateWait(); - LOGGER.debug(String.format("Waiting after clicking element by test id '%s' finished", dataTestId)); + try { + clickOnElementByTestIdWithoutWait(dataTestId); + ultimateWait(); + }catch (Exception e) { + LOGGER.debug("", e); + } } - public static void clickOnElementChildByTestId(String dataTestId) { - clickOnElementChildByTestIdWithoutWait(dataTestId); - ultimateWait(); + public static boolean tryToclickOnElementByTestId(String dataTestId, int timeOut) { + try { + clickOnElementByTestId(dataTestId, timeOut); + ultimateWait(); + return true; + } catch (Exception e) { + LOGGER.debug("", e); + return false; + } } - public static void clickOnElementByTestIdWithoutWait(final String dataTestId) { - final WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); - wait - .until(ExpectedConditions.elementToBeClickable(By.xpath(String.format(DATA_TESTS_ID, dataTestId)))).click(); + public static void clickOnElementByTestIdWithoutWait(String dataTestId) { + WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); + try { + wait.until(ExpectedConditions + .elementToBeClickable(By.xpath(String.format(DATA_TESTS_ID, dataTestId, "']")))).click(); + getExtendTest().log(Status.INFO, String.format("Click on element ", DATA_TESTS_ID, dataTestId, "']")); + } catch (Exception e) { + ExtentTestActions.log(Status.FAIL, dataTestId + " element isn't clickable"); + ExtentTestActions.log(Status.FAIL, e); + } } - public static void clickOnElementChildByTestIdWithoutWait(String dataTestId) { + public static void clickOnElementByInputTestIdWithoutWait(String dataTestId) { WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); - wait.until(ExpectedConditions.elementToBeClickable(By.xpath(String.format(DATA_TESTS_ID, dataTestId) + "//*"))).click(); + wait.until(ExpectedConditions.elementToBeClickable(By.xpath(String.format(DATA_TESTS_ID, dataTestId, "']//*")))).click(); } public static void clickOnElementByTestId(String dataTestId, int customTimeout) { WebDriverWait wait = new WebDriverWait(getDriver(), customTimeout); - wait.until(ExpectedConditions.elementToBeClickable(By.xpath(String.format(DATA_TESTS_ID, dataTestId)))).click(); + wait.until(ExpectedConditions.elementToBeClickable(By.xpath(String.format(DATA_TESTS_ID, dataTestId, "']")))).click(); } public static WebElement waitForElementVisibilityByTestId(String dataTestId) { WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); - return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(String.format(DATA_TESTS_ID, dataTestId)))); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(String.format(DATA_TESTS_ID, dataTestId, "']")))); + } + + public static WebElement waitForElementVisibilityByClass(String className) { + WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(String.format("//*[contains(@class, '", className, "')]")))); } public static Boolean waitForElementInVisibilityByTestId(String dataTestId) { @@ -265,10 +289,9 @@ public final class GeneralUIUtils { public static Boolean waitForElementInVisibilityByTestId(String dataTestId, int timeOut) { WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); - boolean displayed = getDriver().findElements(By.xpath(String.format(DATA_TESTS_ID, dataTestId))).isEmpty(); + boolean displayed = getDriver().findElements(By.xpath(String.format(DATA_TESTS_ID, dataTestId, "']"))).isEmpty(); if (!displayed) { - Boolean until = wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath(String.format(DATA_TESTS_ID, dataTestId)))); - ultimateWait(); + Boolean until = wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath(String.format(DATA_TESTS_ID, dataTestId, "'])")))); return until; } return false; @@ -363,7 +386,7 @@ public final class GeneralUIUtils { } public static void moveToStep(final String dataTestId) { - clickOnElementChildByTestId(dataTestId); + clickOnElementByTestId(dataTestId); } @@ -393,7 +416,7 @@ public final class GeneralUIUtils { public static WebElement getSelectedElementFromDropDown(String dataTestId) { GeneralUIUtils.ultimateWait(); - return new Select(getDriver().findElement(By.xpath(String.format(DATA_TESTS_ID, dataTestId)))).getFirstSelectedOption(); + return new Select(getDriver().findElement(By.xpath(String.format(DATA_TESTS_ID, dataTestId, "']")))).getFirstSelectedOption(); } public static boolean checkElementsCountInTable(int expectedElementsCount, Supplier> func) { @@ -419,7 +442,7 @@ public final class GeneralUIUtils { func.run(); long estimateTime = System.nanoTime(); long duration = TimeUnit.NANOSECONDS.toSeconds(estimateTime - startTime); - return String.format("%02d:%02d", duration / DURATION_FORMATIN, duration % DURATION_FORMATIN); + return String.format("%02`d:%02d", duration / DURATION_FORMATIN, duration % DURATION_FORMATIN); } public static WebElement clickOnAreaJS(String areaId) { diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/NotificationHelper.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/NotificationHelper.java index 89ff4e7b98..6366447e70 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/NotificationHelper.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/NotificationHelper.java @@ -19,10 +19,6 @@ package org.openecomp.sdc.ci.tests.utilities; -import static org.openecomp.sdc.ci.tests.utilities.NotificationHelper.XpathSelector.MAIN_CONTAINER_DIV; -import static org.openecomp.sdc.ci.tests.utilities.NotificationHelper.XpathSelector.MESSAGE_CONTENT_DIV; -import static org.openecomp.sdc.ci.tests.utilities.NotificationHelper.XpathSelector.MESSAGE_SUCCESS_DIV; - import org.openecomp.sdc.ci.tests.execute.setup.DriverFactory; import org.openqa.selenium.By; import org.openqa.selenium.support.ui.ExpectedConditions; @@ -30,6 +26,10 @@ import org.openqa.selenium.support.ui.WebDriverWait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.openecomp.sdc.ci.tests.utilities.NotificationHelper.XpathSelector.MAIN_CONTAINER_DIV; +import static org.openecomp.sdc.ci.tests.utilities.NotificationHelper.XpathSelector.MESSAGE_CONTENT_DIV; +import static org.openecomp.sdc.ci.tests.utilities.NotificationHelper.XpathSelector.MESSAGE_SUCCESS_DIV; + public class NotificationHelper { private static final Logger LOGGER = LoggerFactory.getLogger(NotificationHelper.class); diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUiUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUiUtils.java index d4d2731c1e..6bc08ec81e 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUiUtils.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUiUtils.java @@ -22,11 +22,11 @@ package org.openecomp.sdc.ci.tests.utilities; import com.aventstack.extentreports.Status; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; import org.openecomp.sdc.ci.tests.datatypes.LifeCycleStateEnum; import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject; import org.openecomp.sdc.ci.tests.execute.devCI.ArtifactFromCsar; import org.openecomp.sdc.ci.tests.execute.setup.ArtifactsCorrelationManager; @@ -59,7 +59,8 @@ public class OnboardingUiUtils { if (vspFound) { List elementsFromTable = GeneralPageElements.getElementsFromTable(); - elementsFromTable.get(1).click(); + elementsFromTable.get(0).click(); + elementsFromTable.get(0).click(); GeneralUIUtils.waitForLoader(); if (isUpdate) { @@ -184,7 +185,7 @@ public class OnboardingUiUtils { validateDeploymentArtifactsVersion(deploymentArtifacts, heatEnvFilesFromCSAR); - DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile); +// DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile); return createVendorSoftwareProduct; } diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PortMirroringUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PortMirroringUtils.java index e26e5f3219..062d11eb9f 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PortMirroringUtils.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PortMirroringUtils.java @@ -29,7 +29,6 @@ import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.CanvasElement; import org.openecomp.sdc.ci.tests.datatypes.CanvasManager; import org.openecomp.sdc.ci.tests.datatypes.ConnectionWizardPopUpObject; @@ -40,6 +39,7 @@ import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; import org.openecomp.sdc.ci.tests.datatypes.ServiceContainer; import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; import org.openecomp.sdc.ci.tests.datatypes.TopMenuButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.VendorLicenseModel; import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject; import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum; diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ProductUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ProductUIUtils.java index 63ff158d24..33c6317590 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ProductUIUtils.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ProductUIUtils.java @@ -21,7 +21,6 @@ package org.openecomp.sdc.ci.tests.utilities; import com.aventstack.extentreports.Status; -import org.junit.rules.TestName; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ServiceUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ServiceUIUtils.java index 2e5ba74f91..41a540ce7b 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ServiceUIUtils.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ServiceUIUtils.java @@ -21,8 +21,6 @@ package org.openecomp.sdc.ci.tests.utilities; import com.aventstack.extentreports.Status; -import java.util.ArrayList; -import java.util.List; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; @@ -30,11 +28,13 @@ import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum; import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; import org.openecomp.sdc.ci.tests.pages.GeneralPageElements; -import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; import org.openecomp.sdc.ci.tests.pages.ServiceGeneralPage; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; +import java.util.ArrayList; +import java.util.List; + public class ServiceUIUtils { private ServiceUIUtils() { @@ -54,11 +54,12 @@ public class ServiceUIUtils { public static void fillServiceGeneralPage(final ServiceReqDetails service) { SetupCDTest.getExtendTest().log(Status.INFO, "Fill in metadata values in general page"); ServiceGeneralPage.defineName(service.getName()); - ResourceGeneralPage.defineDescription(service.getDescription()); - ResourceGeneralPage.defineCategory(service.getCategories().get(0).getName()); - ServiceGeneralPage.defineProjectCode(service.getProjectCode()); + ServiceGeneralPage.defineDescription(service.getDescription()); + ServiceGeneralPage.defineCategory(service.getCategories().get(0).getName()); + ServiceGeneralPage.defineServiceFunction(service.getServiceFunction()); + ServiceGeneralPage.defineNamingPolicy(service.getNamingPolicy()); defineTagsList2(service.getTags()); - ResourceGeneralPage.defineContactId(service.getContactId()); + ServiceGeneralPage.defineContactId(service.getContactId()); GeneralUIUtils.clickSomewhereOnPage(); } diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/CatalogVerificator.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/CatalogVerificator.java index d2aa1497ec..470f2966b3 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/CatalogVerificator.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/CatalogVerificator.java @@ -156,10 +156,6 @@ public class CatalogVerificator { } else { return LifeCycleStateEnum.CERTIFIED; } - case READY_FOR_CERTIFICATION: - return LifeCycleStateEnum.READY_FOR_TESTING; - case CERTIFICATION_IN_PROGRESS: - return LifeCycleStateEnum.IN_TESTING; case NOT_CERTIFIED_CHECKIN: return LifeCycleStateEnum.CHECKIN; //to IN DESIGN case NOT_CERTIFIED_CHECKOUT: diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java index 4110985781..1e6a0c37df 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java @@ -68,44 +68,45 @@ public class ServiceVerificator { private ServiceVerificator() { } - public static void verifyNumOfComponentInstances(ComponentReqDetails component, String version, int numOfVFC, - User user) { - SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifing the number of components on the canvas; should be %s", numOfVFC)); - String responseAfterDrag = null; - component.setVersion(version); - if (component instanceof ServiceReqDetails) { - responseAfterDrag = RestCDUtils.getService((ServiceReqDetails) component, user).getResponse(); - } else if (component instanceof ResourceReqDetails) { - responseAfterDrag = RestCDUtils.getResource((ResourceReqDetails) component, user).getResponse(); - } - int size = 0; - JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); - if (jsonResource.get("componentInstances") != null) { - size = ((JSONArray) jsonResource.get("componentInstances")).size(); - assertTrue(size == numOfVFC, "Expected number of componenet instances is " + numOfVFC + ", but actual is " + size); - ExtentTestActions.log(Status.INFO, "The number of components on the canvas was verified."); - } else { - assertTrue(false, "Expected number of componenet instances is " + numOfVFC + ", but actual is " + size); - } - } - - public static void verifyServiceUpdatedInUI(ServiceReqDetails service) { - assertTrue(service.getName().equals(ResourceGeneralPage.getNameText())); - assertTrue(service.getDescription().equals(ResourceGeneralPage.getDescriptionText())); - assertTrue(service.getCategory().equals(ServiceGeneralPage.getCategoryText())); - assertTrue(service.getProjectCode().equals(ServiceGeneralPage.getProjectCodeText())); - for (String tag : ServiceGeneralPage.getTags()) { - assertTrue(service.getTags().contains(tag)); - } - assertTrue(service.getContactId().equals(ResourceGeneralPage.getContactIdText())); - } - - public static void verifyServiceDeletedInUI(ServiceReqDetails service) throws InterruptedException { - Thread.sleep(SLEEP_TIME); - List cardElements = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DashboardCardEnum.DASHBOARD_CARD.getValue()); - if (!(cardElements.isEmpty())) { - for (WebElement cardElement : cardElements) { - WebElement componentName = GeneralUIUtils.getElementfromElementByCSS(cardElement, + public static void verifyNumOfComponentInstances(ComponentReqDetails component, String version, int numOfVFC, + User user) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifing the number of components on the canvas; should be %s", numOfVFC)); + String responseAfterDrag = null; + component.setVersion(version); + if (component instanceof ServiceReqDetails) { + responseAfterDrag = RestCDUtils.getService((ServiceReqDetails) component, user).getResponse(); + } else if (component instanceof ResourceReqDetails) { + responseAfterDrag = RestCDUtils.getResource((ResourceReqDetails) component, user).getResponse(); + } + int size = 0; + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + if(jsonResource.get("componentInstances")!= null){ + size = ((JSONArray) jsonResource.get("componentInstances")).size(); + assertTrue(size == numOfVFC, "Expected number of componenet instances is " + numOfVFC + ", but actual is " + size); + ExtentTestActions.log(Status.INFO, "The number of components on the canvas was verified."); + }else{ + assertTrue(false, "Expected number of componenet instances is " + numOfVFC + ", but actual is " + size); + } + } + + public static void verifyServiceUpdatedInUI(ServiceReqDetails service) { + assertTrue(service.getName().equals(ResourceGeneralPage.getNameText())); + assertTrue(service.getDescription().equals(ResourceGeneralPage.getDescriptionText())); + assertTrue(service.getCategory().equals(ServiceGeneralPage.getCategoryText())); + assertTrue(service.getServiceFunction().equals(ServiceGeneralPage.getServiceFunctionText())); + assertTrue(service.getNamingPolicy().equals(ServiceGeneralPage.getNamingPolicyText())); + for(String tag: ServiceGeneralPage.getTags()){ + assertTrue(service.getTags().contains(tag)); + } + assertTrue(service.getContactId().equals(ResourceGeneralPage.getContactIdText())); + } + + public static void verifyServiceDeletedInUI(ServiceReqDetails service) throws InterruptedException { + Thread.sleep(1000); + List cardElements = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DashboardCardEnum.DASHBOARD_CARD.getValue()); + if (!(cardElements.isEmpty())){ + for (WebElement cardElement: cardElements){ + WebElement componentName = GeneralUIUtils.getElementfromElementByCSS(cardElement, DataTestIdEnum.DashboardCardEnum.INFO_NAME.getValue()); WebElement componentType = GeneralUIUtils.getElementfromElementByCSS(cardElement, DataTestIdEnum.DashboardCardEnum.ASSET_TYPE_CSS.getValue()); diff --git a/ui-ci/src/main/resources/ci/conf/attsdc.yaml b/ui-ci/src/main/resources/ci/conf/attsdc.yaml index 64c42dccc9..e7dfa39570 100644 --- a/ui-ci/src/main/resources/ci/conf/attsdc.yaml +++ b/ui-ci/src/main/resources/ci/conf/attsdc.yaml @@ -1,17 +1,17 @@ outputFolder: target reportName: index.html -catalogBeHost: 192.168.33.10 +catalogBeHost: localhost esHost: eshost disributionClientHost: disClient catalogFePort: 8181 -catalogBePort: 8080 +catalogBePort: 8284 disributionClientPort: 8181 esPort: 9200 neoHost: neoHost neoPort: 7474 neoDBusername: neo4j neoDBpassword: 123456 -url: http://192.168.33.10:8285/sdc1 +url: http://localhost:8285/sdc1 #url: https://www.e-access.att.com/QA-AUTOMATE1/sdc1/portal #url: https://www.e-access.att.com/AA-IFT-testing/sdc1/portal #url: https://www.e-access.att.com/QA-SCRUM1/sdc1/portal @@ -40,8 +40,8 @@ janusGraphPropertiesFile: src/main/resources/ci/conf/janusgraph.properties stopOnClassFailure: false #todo -onboardingBeHost: 192.168.33.10 -onboardingBePort: 8080 +onboardingBeHost: localhost +onboardingBePort: 8283 #List of non-abstract resources to keep during JanusGraph cleanup between tests #Only 1.0 version will be kept resourcesNotToDelete: diff --git a/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/templates/default/SDC-Simulator-webseal.conf.erb b/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/templates/default/SDC-Simulator-webseal.conf.erb index e4c5d753fa..4cdd4fbfba 100644 --- a/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/templates/default/SDC-Simulator-webseal.conf.erb +++ b/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/templates/default/SDC-Simulator-webseal.conf.erb @@ -1,6 +1,7 @@ { webseal { fe="<%= @fe_url %>" + portalCookieName="EPService" users = [ { userId="cs0008" diff --git a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/Login.java b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/Login.java index 4c807f4912..9780c09936 100644 --- a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/Login.java +++ b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/Login.java @@ -148,6 +148,7 @@ public class Login extends HttpServlet { response.addCookie(cookieLastName); response.addCookie(cookieRemoteAddress); response.addCookie(cookieWsType); + response.addCookie(new Cookie(Conf.getInstance().getPortalCookieName(), "portal")); response.sendRedirect("/sdc1"); } diff --git a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/conf/Conf.java b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/conf/Conf.java index 6b5103f51c..449fe62f49 100644 --- a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/conf/Conf.java +++ b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/conf/Conf.java @@ -31,10 +31,19 @@ import java.util.Map; public class Conf { - private static Conf conf= null; + private static Conf conf = new Conf(); private String feHost; - Map users = new HashMap(); - + private Map users = new HashMap(); + private String portalCookieName; + + private void setPortalCookieName(String portalCookieName) { + this.portalCookieName = portalCookieName; + } + + public String getPortalCookieName() { + return portalCookieName; + } + private Conf(){ initConf(); } @@ -50,7 +59,9 @@ public class Conf { Config confFile = ConfigFactory.parseFileAnySyntax(new File(confPath)); Config resolve = confFile.resolve(); setFeHost(resolve.getString("webseal.fe")); - List list = resolve.getConfigList("webseal.users"); + setPortalCookieName(resolve.getString("webseal.portalCookieName")); + List list = resolve.getConfigList("webseal.users"); + for (Config conf : list ){ String userId = conf.getString("userId"); String password = conf.getString("password"); @@ -67,9 +78,6 @@ public class Conf { } public static Conf getInstance(){ - if (conf == null){ - conf = new Conf(); - } return conf; } -- 2.16.6